diff --git a/en/api/Phalcon_Acl_Adapter_Memory.rst b/en/api/Phalcon_Acl_Adapter_Memory.rst index 008bc63dd390..087edf7c34fb 100644 --- a/en/api/Phalcon_Acl_Adapter_Memory.rst +++ b/en/api/Phalcon_Acl_Adapter_Memory.rst @@ -10,58 +10,68 @@ Class **Phalcon\\Acl\\Adapter\\Memory** :raw-html:`Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/en/api/Phalcon_Annotations_Adapter_Apc.rst b/en/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/en/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/en/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/en/api/Phalcon_Annotations_Adapter_Files.rst b/en/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/en/api/Phalcon_Annotations_Adapter_Files.rst +++ b/en/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/en/api/Phalcon_Annotations_Adapter_Memory.rst b/en/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/en/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/en/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/en/api/Phalcon_Annotations_Adapter_Xcache.rst b/en/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/en/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/en/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/en/api/Phalcon_Annotations_Reflection.rst b/en/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/en/api/Phalcon_Annotations_Reflection.rst +++ b/en/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/en/api/Phalcon_Application.rst b/en/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/en/api/Phalcon_Application.rst +++ b/en/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/en/api/Phalcon_Assets_Filters_Cssmin.rst b/en/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/en/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/en/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/en/api/Phalcon_Assets_Filters_Jsmin.rst b/en/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/en/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/en/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/en/api/Phalcon_Assets_Inline.rst b/en/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/en/api/Phalcon_Assets_Inline.rst +++ b/en/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/en/api/Phalcon_Assets_Resource.rst b/en/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/en/api/Phalcon_Assets_Resource.rst +++ b/en/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/en/api/Phalcon_Assets_Resource_Js.rst b/en/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/en/api/Phalcon_Assets_Resource_Js.rst +++ b/en/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/en/api/Phalcon_Cache_Backend.rst b/en/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/en/api/Phalcon_Cache_Backend.rst +++ b/en/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/en/api/Phalcon_Cache_Backend_Apc.rst b/en/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/en/api/Phalcon_Cache_Backend_Apc.rst +++ b/en/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/en/api/Phalcon_Cache_Backend_File.rst b/en/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/en/api/Phalcon_Cache_Backend_File.rst +++ b/en/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/en/api/Phalcon_Cache_Backend_Libmemcached.rst b/en/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/en/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/en/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/en/api/Phalcon_Cache_Backend_Memcache.rst b/en/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/en/api/Phalcon_Cache_Backend_Memcache.rst +++ b/en/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/en/api/Phalcon_Cache_Backend_Memory.rst b/en/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/en/api/Phalcon_Cache_Backend_Memory.rst +++ b/en/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/en/api/Phalcon_Cache_Backend_Mongo.rst b/en/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/en/api/Phalcon_Cache_Backend_Mongo.rst +++ b/en/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/en/api/Phalcon_Cache_Backend_Redis.rst b/en/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/en/api/Phalcon_Cache_Backend_Redis.rst +++ b/en/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/en/api/Phalcon_Cache_Backend_Xcache.rst b/en/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/en/api/Phalcon_Cache_Backend_Xcache.rst +++ b/en/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/en/api/Phalcon_Cache_Frontend_Base64.rst b/en/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/en/api/Phalcon_Cache_Frontend_Base64.rst +++ b/en/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/en/api/Phalcon_Cache_Frontend_Data.rst b/en/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/en/api/Phalcon_Cache_Frontend_Data.rst +++ b/en/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/en/api/Phalcon_Cache_Frontend_Igbinary.rst b/en/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/en/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/en/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/en/api/Phalcon_Cache_Frontend_Json.rst b/en/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/en/api/Phalcon_Cache_Frontend_Json.rst +++ b/en/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/en/api/Phalcon_Cache_Frontend_Msgpack.rst b/en/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/en/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/en/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/en/api/Phalcon_Cache_Frontend_None.rst b/en/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/en/api/Phalcon_Cache_Frontend_None.rst +++ b/en/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/en/api/Phalcon_Cache_Frontend_Output.rst b/en/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/en/api/Phalcon_Cache_Frontend_Output.rst +++ b/en/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/en/api/Phalcon_Cache_Multiple.rst b/en/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/en/api/Phalcon_Cache_Multiple.rst +++ b/en/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/en/api/Phalcon_Cli_Console.rst b/en/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/en/api/Phalcon_Cli_Console.rst +++ b/en/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/en/api/Phalcon_Cli_Dispatcher.rst b/en/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/en/api/Phalcon_Cli_Dispatcher.rst +++ b/en/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/en/api/Phalcon_Cli_Router.rst b/en/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/en/api/Phalcon_Cli_Router.rst +++ b/en/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/en/api/Phalcon_Cli_Router_Route.rst b/en/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/en/api/Phalcon_Cli_Router_Route.rst +++ b/en/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/en/api/Phalcon_Cli_Task.rst b/en/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/en/api/Phalcon_Cli_Task.rst +++ b/en/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/en/api/Phalcon_Config.rst b/en/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/en/api/Phalcon_Config.rst +++ b/en/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/en/api/Phalcon_Config_Adapter_Ini.rst b/en/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/en/api/Phalcon_Config_Adapter_Ini.rst +++ b/en/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/en/api/Phalcon_Config_Adapter_Json.rst b/en/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/en/api/Phalcon_Config_Adapter_Json.rst +++ b/en/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/en/api/Phalcon_Config_Adapter_Php.rst b/en/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/en/api/Phalcon_Config_Adapter_Php.rst +++ b/en/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/en/api/Phalcon_Config_Adapter_Yaml.rst b/en/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/en/api/Phalcon_Config_Adapter_Yaml.rst +++ b/en/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/en/api/Phalcon_Crypt.rst b/en/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/en/api/Phalcon_Crypt.rst +++ b/en/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/en/api/Phalcon_Db.rst b/en/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/en/api/Phalcon_Db.rst +++ b/en/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/en/api/Phalcon_Db_Adapter.rst b/en/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/en/api/Phalcon_Db_Adapter.rst +++ b/en/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/en/api/Phalcon_Db_Adapter_Pdo.rst b/en/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/en/api/Phalcon_Db_Adapter_Pdo.rst +++ b/en/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/en/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/en/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/en/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/en/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/en/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/en/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/en/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/en/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/en/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/en/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/en/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/en/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/en/api/Phalcon_Db_Column.rst b/en/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/en/api/Phalcon_Db_Column.rst +++ b/en/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/en/api/Phalcon_Db_Dialect.rst b/en/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/en/api/Phalcon_Db_Dialect.rst +++ b/en/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/en/api/Phalcon_Db_Dialect_Mysql.rst b/en/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/en/api/Phalcon_Db_Dialect_Mysql.rst +++ b/en/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/en/api/Phalcon_Db_Dialect_Postgresql.rst b/en/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/en/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/en/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/en/api/Phalcon_Db_Dialect_Sqlite.rst b/en/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/en/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/en/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/en/api/Phalcon_Db_Index.rst b/en/api/Phalcon_Db_Index.rst index 3c6f460563a7..415a456a64bd 100644 --- a/en/api/Phalcon_Db_Index.rst +++ b/en/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods @@ -43,3 +45,4 @@ public static **__set_state** (*array* $data) Restore a Phalcon\\Db\\Index object from export + diff --git a/en/api/Phalcon_Db_Profiler.rst b/en/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/en/api/Phalcon_Db_Profiler.rst +++ b/en/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/en/api/Phalcon_Db_RawValue.rst b/en/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/en/api/Phalcon_Db_RawValue.rst +++ b/en/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/en/api/Phalcon_Db_Reference.rst b/en/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/en/api/Phalcon_Db_Reference.rst +++ b/en/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/en/api/Phalcon_Db_Result_Pdo.rst b/en/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/en/api/Phalcon_Db_Result_Pdo.rst +++ b/en/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/en/api/Phalcon_Debug.rst b/en/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/en/api/Phalcon_Debug.rst +++ b/en/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/en/api/Phalcon_Debug_Dump.rst b/en/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/en/api/Phalcon_Debug_Dump.rst +++ b/en/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/en/api/Phalcon_Di.rst b/en/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/en/api/Phalcon_Di.rst +++ b/en/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/en/api/Phalcon_Di_FactoryDefault.rst b/en/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/en/api/Phalcon_Di_FactoryDefault.rst +++ b/en/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/en/api/Phalcon_Di_FactoryDefault_Cli.rst b/en/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/en/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/en/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/en/api/Phalcon_Di_Injectable.rst b/en/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/en/api/Phalcon_Di_Injectable.rst +++ b/en/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/en/api/Phalcon_Di_Service.rst b/en/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/en/api/Phalcon_Di_Service.rst +++ b/en/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/en/api/Phalcon_Dispatcher.rst b/en/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/en/api/Phalcon_Dispatcher.rst +++ b/en/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/en/api/Phalcon_Escaper.rst b/en/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/en/api/Phalcon_Escaper.rst +++ b/en/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/en/api/Phalcon_Events_Event.rst b/en/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/en/api/Phalcon_Events_Event.rst +++ b/en/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/en/api/Phalcon_Events_Manager.rst b/en/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/en/api/Phalcon_Events_Manager.rst +++ b/en/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/en/api/Phalcon_Filter.rst b/en/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/en/api/Phalcon_Filter.rst +++ b/en/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/en/api/Phalcon_Flash.rst b/en/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/en/api/Phalcon_Flash.rst +++ b/en/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/en/api/Phalcon_Flash_Direct.rst b/en/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/en/api/Phalcon_Flash_Direct.rst +++ b/en/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/en/api/Phalcon_Flash_Session.rst b/en/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/en/api/Phalcon_Flash_Session.rst +++ b/en/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/en/api/Phalcon_Forms_Element.rst b/en/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/en/api/Phalcon_Forms_Element.rst +++ b/en/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_Check.rst b/en/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/en/api/Phalcon_Forms_Element_Check.rst +++ b/en/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_Date.rst b/en/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/en/api/Phalcon_Forms_Element_Date.rst +++ b/en/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_Email.rst b/en/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/en/api/Phalcon_Forms_Element_Email.rst +++ b/en/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_File.rst b/en/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/en/api/Phalcon_Forms_Element_File.rst +++ b/en/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_Hidden.rst b/en/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/en/api/Phalcon_Forms_Element_Hidden.rst +++ b/en/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_Numeric.rst b/en/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/en/api/Phalcon_Forms_Element_Numeric.rst +++ b/en/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_Password.rst b/en/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/en/api/Phalcon_Forms_Element_Password.rst +++ b/en/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_Radio.rst b/en/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/en/api/Phalcon_Forms_Element_Radio.rst +++ b/en/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_Select.rst b/en/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/en/api/Phalcon_Forms_Element_Select.rst +++ b/en/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_Submit.rst b/en/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/en/api/Phalcon_Forms_Element_Submit.rst +++ b/en/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_Text.rst b/en/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/en/api/Phalcon_Forms_Element_Text.rst +++ b/en/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Element_TextArea.rst b/en/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/en/api/Phalcon_Forms_Element_TextArea.rst +++ b/en/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/en/api/Phalcon_Forms_Manager.rst b/en/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/en/api/Phalcon_Forms_Manager.rst +++ b/en/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/en/api/Phalcon_Http_Cookie.rst b/en/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/en/api/Phalcon_Http_Cookie.rst +++ b/en/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/en/api/Phalcon_Http_Request.rst b/en/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/en/api/Phalcon_Http_Request.rst +++ b/en/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/en/api/Phalcon_Http_Request_File.rst b/en/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/en/api/Phalcon_Http_Request_File.rst +++ b/en/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/en/api/Phalcon_Http_Response.rst b/en/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/en/api/Phalcon_Http_Response.rst +++ b/en/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/en/api/Phalcon_Http_Response_Cookies.rst b/en/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/en/api/Phalcon_Http_Response_Cookies.rst +++ b/en/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/en/api/Phalcon_Image_Adapter.rst b/en/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/en/api/Phalcon_Image_Adapter.rst +++ b/en/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/en/api/Phalcon_Image_Adapter_Gd.rst b/en/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/en/api/Phalcon_Image_Adapter_Gd.rst +++ b/en/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/en/api/Phalcon_Image_Adapter_Imagick.rst b/en/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/en/api/Phalcon_Image_Adapter_Imagick.rst +++ b/en/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/en/api/Phalcon_Loader.rst b/en/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/en/api/Phalcon_Loader.rst +++ b/en/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/en/api/Phalcon_Logger_Adapter.rst b/en/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/en/api/Phalcon_Logger_Adapter.rst +++ b/en/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/en/api/Phalcon_Logger_Adapter_File.rst b/en/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/en/api/Phalcon_Logger_Adapter_File.rst +++ b/en/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/en/api/Phalcon_Logger_Adapter_Firephp.rst b/en/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/en/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/en/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/en/api/Phalcon_Logger_Adapter_Stream.rst b/en/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/en/api/Phalcon_Logger_Adapter_Stream.rst +++ b/en/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/en/api/Phalcon_Logger_Adapter_Syslog.rst b/en/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/en/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/en/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/en/api/Phalcon_Mvc_Application.rst b/en/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/en/api/Phalcon_Mvc_Application.rst +++ b/en/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/en/api/Phalcon_Mvc_Collection.rst b/en/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/en/api/Phalcon_Mvc_Collection.rst +++ b/en/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/en/api/Phalcon_Mvc_Collection_Behavior.rst b/en/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/en/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/en/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/en/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/en/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/en/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/en/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/en/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/en/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/en/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/en/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/en/api/Phalcon_Mvc_Collection_Document.rst b/en/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/en/api/Phalcon_Mvc_Collection_Document.rst +++ b/en/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/en/api/Phalcon_Mvc_Collection_Manager.rst b/en/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/en/api/Phalcon_Mvc_Collection_Manager.rst +++ b/en/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/en/api/Phalcon_Mvc_Controller.rst b/en/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/en/api/Phalcon_Mvc_Controller.rst +++ b/en/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/en/api/Phalcon_Mvc_Dispatcher.rst b/en/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/en/api/Phalcon_Mvc_Dispatcher.rst +++ b/en/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/en/api/Phalcon_Mvc_Micro.rst b/en/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/en/api/Phalcon_Mvc_Micro.rst +++ b/en/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/en/api/Phalcon_Mvc_Model.rst b/en/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/en/api/Phalcon_Mvc_Model.rst +++ b/en/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/en/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/en/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/en/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/en/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/en/api/Phalcon_Mvc_Model_Criteria.rst b/en/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/en/api/Phalcon_Mvc_Model_Criteria.rst +++ b/en/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/en/api/Phalcon_Mvc_Model_Manager.rst b/en/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/en/api/Phalcon_Mvc_Model_Manager.rst +++ b/en/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/en/api/Phalcon_Mvc_Model_Message.rst b/en/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/en/api/Phalcon_Mvc_Model_Message.rst +++ b/en/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/en/api/Phalcon_Mvc_Model_MetaData.rst b/en/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/en/api/Phalcon_Mvc_Model_MetaData.rst +++ b/en/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/en/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/en/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/en/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/en/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/en/api/Phalcon_Mvc_Model_MetaData_Files.rst b/en/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/en/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/en/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/en/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/en/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/en/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/en/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/en/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/en/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/en/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/en/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/en/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/en/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/en/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/en/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/en/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/en/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/en/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/en/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/en/api/Phalcon_Mvc_Model_MetaData_Session.rst b/en/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/en/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/en/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/en/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/en/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/en/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/en/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/en/api/Phalcon_Mvc_Model_Query.rst b/en/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/en/api/Phalcon_Mvc_Model_Query.rst +++ b/en/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/en/api/Phalcon_Mvc_Model_Query_Builder.rst b/en/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/en/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/en/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/en/api/Phalcon_Mvc_Model_Query_Lang.rst b/en/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/en/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/en/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/en/api/Phalcon_Mvc_Model_Relation.rst b/en/api/Phalcon_Mvc_Model_Relation.rst index bbd49acbd3ac..7a0c5587b554 100644 --- a/en/api/Phalcon_Mvc_Model_Relation.rst +++ b/en/api/Phalcon_Mvc_Model_Relation.rst @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned diff --git a/en/api/Phalcon_Mvc_Model_Resultset.rst b/en/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/en/api/Phalcon_Mvc_Model_Resultset.rst +++ b/en/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/en/api/Phalcon_Mvc_Model_Transaction.rst b/en/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/en/api/Phalcon_Mvc_Model_Transaction.rst +++ b/en/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/en/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/en/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/en/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/en/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/en/api/Phalcon_Mvc_Model_ValidationFailed.rst b/en/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/en/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/en/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/en/api/Phalcon_Mvc_Model_Validator.rst b/en/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/en/api/Phalcon_Mvc_Model_Validator.rst +++ b/en/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/en/api/Phalcon_Mvc_Model_Validator_Email.rst b/en/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/en/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/en/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/en/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/en/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/en/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/en/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/en/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/en/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/en/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/en/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/en/api/Phalcon_Mvc_Model_Validator_Ip.rst b/en/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/en/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/en/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/en/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/en/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/en/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/en/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/en/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/en/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/en/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/en/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/en/api/Phalcon_Mvc_Model_Validator_Regex.rst b/en/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/en/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/en/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/en/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/en/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/en/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/en/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/en/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/en/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/en/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/en/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/en/api/Phalcon_Mvc_Model_Validator_Url.rst b/en/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/en/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/en/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/en/api/Phalcon_Mvc_Router.rst b/en/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/en/api/Phalcon_Mvc_Router.rst +++ b/en/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/en/api/Phalcon_Mvc_Router_Annotations.rst b/en/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/en/api/Phalcon_Mvc_Router_Annotations.rst +++ b/en/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/en/api/Phalcon_Mvc_Router_Group.rst b/en/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/en/api/Phalcon_Mvc_Router_Group.rst +++ b/en/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/en/api/Phalcon_Mvc_Router_Route.rst b/en/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/en/api/Phalcon_Mvc_Router_Route.rst +++ b/en/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/en/api/Phalcon_Mvc_Url.rst b/en/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/en/api/Phalcon_Mvc_Url.rst +++ b/en/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/en/api/Phalcon_Mvc_View.rst b/en/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/en/api/Phalcon_Mvc_View.rst +++ b/en/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/en/api/Phalcon_Mvc_View_Engine.rst b/en/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/en/api/Phalcon_Mvc_View_Engine.rst +++ b/en/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/en/api/Phalcon_Mvc_View_Engine_Php.rst b/en/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/en/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/en/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/en/api/Phalcon_Mvc_View_Engine_Volt.rst b/en/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/en/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/en/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/en/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/en/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/en/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/en/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/en/api/Phalcon_Mvc_View_Simple.rst b/en/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/en/api/Phalcon_Mvc_View_Simple.rst +++ b/en/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/en/api/Phalcon_Paginator_Adapter.rst b/en/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/en/api/Phalcon_Paginator_Adapter.rst +++ b/en/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/en/api/Phalcon_Paginator_Adapter_Model.rst b/en/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/en/api/Phalcon_Paginator_Adapter_Model.rst +++ b/en/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/en/api/Phalcon_Paginator_Adapter_NativeArray.rst b/en/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/en/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/en/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/en/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/en/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/en/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/en/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/en/api/Phalcon_Queue_Beanstalk.rst b/en/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/en/api/Phalcon_Queue_Beanstalk.rst +++ b/en/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/en/api/Phalcon_Queue_Beanstalk_Job.rst b/en/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/en/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/en/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/en/api/Phalcon_Registry.rst b/en/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/en/api/Phalcon_Registry.rst +++ b/en/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/en/api/Phalcon_Security.rst b/en/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/en/api/Phalcon_Security.rst +++ b/en/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/en/api/Phalcon_Security_Random.rst b/en/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/en/api/Phalcon_Security_Random.rst +++ b/en/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/en/api/Phalcon_Session_Adapter.rst b/en/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/en/api/Phalcon_Session_Adapter.rst +++ b/en/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/en/api/Phalcon_Session_Adapter_Files.rst b/en/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/en/api/Phalcon_Session_Adapter_Files.rst +++ b/en/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/en/api/Phalcon_Session_Adapter_Libmemcached.rst b/en/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/en/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/en/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/en/api/Phalcon_Session_Adapter_Memcache.rst b/en/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/en/api/Phalcon_Session_Adapter_Memcache.rst +++ b/en/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/en/api/Phalcon_Session_Adapter_Redis.rst b/en/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/en/api/Phalcon_Session_Adapter_Redis.rst +++ b/en/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/en/api/Phalcon_Session_Bag.rst b/en/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/en/api/Phalcon_Session_Bag.rst +++ b/en/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/en/api/Phalcon_Tag.rst b/en/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/en/api/Phalcon_Tag.rst +++ b/en/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/en/api/Phalcon_Translate_Adapter_Gettext.rst b/en/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/en/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/en/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/en/api/Phalcon_Validation.rst b/en/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/en/api/Phalcon_Validation.rst +++ b/en/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/en/api/Phalcon_Validation_CombinedFieldsValidator.rst b/en/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/en/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/en/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Message.rst b/en/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/en/api/Phalcon_Validation_Message.rst +++ b/en/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/en/api/Phalcon_Validation_Message_Group.rst b/en/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/en/api/Phalcon_Validation_Message_Group.rst +++ b/en/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/en/api/Phalcon_Validation_Validator.rst b/en/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/en/api/Phalcon_Validation_Validator.rst +++ b/en/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Alnum.rst b/en/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/en/api/Phalcon_Validation_Validator_Alnum.rst +++ b/en/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Alpha.rst b/en/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/en/api/Phalcon_Validation_Validator_Alpha.rst +++ b/en/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Between.rst b/en/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/en/api/Phalcon_Validation_Validator_Between.rst +++ b/en/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Confirmation.rst b/en/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/en/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/en/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_CreditCard.rst b/en/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/en/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/en/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Date.rst b/en/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/en/api/Phalcon_Validation_Validator_Date.rst +++ b/en/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Digit.rst b/en/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/en/api/Phalcon_Validation_Validator_Digit.rst +++ b/en/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Email.rst b/en/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/en/api/Phalcon_Validation_Validator_Email.rst +++ b/en/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_ExclusionIn.rst b/en/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/en/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/en/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_File.rst b/en/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/en/api/Phalcon_Validation_Validator_File.rst +++ b/en/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Identical.rst b/en/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/en/api/Phalcon_Validation_Validator_Identical.rst +++ b/en/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_InclusionIn.rst b/en/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/en/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/en/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Numericality.rst b/en/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/en/api/Phalcon_Validation_Validator_Numericality.rst +++ b/en/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_PresenceOf.rst b/en/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/en/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/en/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Regex.rst b/en/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/en/api/Phalcon_Validation_Validator_Regex.rst +++ b/en/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_StringLength.rst b/en/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/en/api/Phalcon_Validation_Validator_StringLength.rst +++ b/en/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Uniqueness.rst b/en/api/Phalcon_Validation_Validator_Uniqueness.rst index 1da8711fa507..8af5174ddfba 100644 --- a/en/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/en/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,69 +10,86 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); - -:: + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; -Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); - -:: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); -In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); - -:: + $validator->add( + "username", + new UniquenessValidator() + ); -Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); - -:: + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); -It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); + -:: Methods ------- @@ -114,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Validation_Validator_Url.rst b/en/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/en/api/Phalcon_Validation_Validator_Url.rst +++ b/en/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/en/api/Phalcon_Version.rst b/en/api/Phalcon_Version.rst index 4322c6cb17bb..77d94d7b0e5a 100644 --- a/en/api/Phalcon_Version.rst +++ b/en/api/Phalcon_Version.rst @@ -27,51 +27,61 @@ 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. +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. final protected static **_getSpecial** (*mixed* $special) -Translates a number to a special release If Special release = 1 this function will return ALPHA +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -Returns the active version (string) +Returns the active version (string) .. code-block:: php Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/es/api/Phalcon_Annotations_Adapter_Apc.rst b/es/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/es/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/es/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/es/api/Phalcon_Annotations_Adapter_Files.rst b/es/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/es/api/Phalcon_Annotations_Adapter_Files.rst +++ b/es/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/es/api/Phalcon_Annotations_Adapter_Memory.rst b/es/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/es/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/es/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/es/api/Phalcon_Annotations_Adapter_Xcache.rst b/es/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/es/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/es/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/es/api/Phalcon_Annotations_Reflection.rst b/es/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/es/api/Phalcon_Annotations_Reflection.rst +++ b/es/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/es/api/Phalcon_Application.rst b/es/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/es/api/Phalcon_Application.rst +++ b/es/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/es/api/Phalcon_Assets_Filters_Cssmin.rst b/es/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/es/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/es/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/es/api/Phalcon_Assets_Filters_Jsmin.rst b/es/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/es/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/es/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/es/api/Phalcon_Assets_Inline.rst b/es/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/es/api/Phalcon_Assets_Inline.rst +++ b/es/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/es/api/Phalcon_Assets_Resource.rst b/es/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/es/api/Phalcon_Assets_Resource.rst +++ b/es/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/es/api/Phalcon_Assets_Resource_Js.rst b/es/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/es/api/Phalcon_Assets_Resource_Js.rst +++ b/es/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/es/api/Phalcon_Cache_Backend.rst b/es/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/es/api/Phalcon_Cache_Backend.rst +++ b/es/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/es/api/Phalcon_Cache_Backend_Apc.rst b/es/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/es/api/Phalcon_Cache_Backend_Apc.rst +++ b/es/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/es/api/Phalcon_Cache_Backend_File.rst b/es/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/es/api/Phalcon_Cache_Backend_File.rst +++ b/es/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/es/api/Phalcon_Cache_Backend_Libmemcached.rst b/es/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/es/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/es/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/es/api/Phalcon_Cache_Backend_Memcache.rst b/es/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/es/api/Phalcon_Cache_Backend_Memcache.rst +++ b/es/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/es/api/Phalcon_Cache_Backend_Memory.rst b/es/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/es/api/Phalcon_Cache_Backend_Memory.rst +++ b/es/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/es/api/Phalcon_Cache_Backend_Mongo.rst b/es/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/es/api/Phalcon_Cache_Backend_Mongo.rst +++ b/es/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/es/api/Phalcon_Cache_Backend_Redis.rst b/es/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/es/api/Phalcon_Cache_Backend_Redis.rst +++ b/es/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/es/api/Phalcon_Cache_Backend_Xcache.rst b/es/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/es/api/Phalcon_Cache_Backend_Xcache.rst +++ b/es/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/es/api/Phalcon_Cache_Frontend_Base64.rst b/es/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/es/api/Phalcon_Cache_Frontend_Base64.rst +++ b/es/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/es/api/Phalcon_Cache_Frontend_Data.rst b/es/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/es/api/Phalcon_Cache_Frontend_Data.rst +++ b/es/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/es/api/Phalcon_Cache_Frontend_Igbinary.rst b/es/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/es/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/es/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/es/api/Phalcon_Cache_Frontend_Json.rst b/es/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/es/api/Phalcon_Cache_Frontend_Json.rst +++ b/es/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/es/api/Phalcon_Cache_Frontend_Msgpack.rst b/es/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/es/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/es/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/es/api/Phalcon_Cache_Frontend_None.rst b/es/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/es/api/Phalcon_Cache_Frontend_None.rst +++ b/es/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/es/api/Phalcon_Cache_Frontend_Output.rst b/es/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/es/api/Phalcon_Cache_Frontend_Output.rst +++ b/es/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/es/api/Phalcon_Cache_Multiple.rst b/es/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/es/api/Phalcon_Cache_Multiple.rst +++ b/es/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/es/api/Phalcon_Cli_Console.rst b/es/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/es/api/Phalcon_Cli_Console.rst +++ b/es/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/es/api/Phalcon_Cli_Dispatcher.rst b/es/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/es/api/Phalcon_Cli_Dispatcher.rst +++ b/es/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/es/api/Phalcon_Cli_Router.rst b/es/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/es/api/Phalcon_Cli_Router.rst +++ b/es/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/es/api/Phalcon_Cli_Router_Route.rst b/es/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/es/api/Phalcon_Cli_Router_Route.rst +++ b/es/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/es/api/Phalcon_Cli_Task.rst b/es/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/es/api/Phalcon_Cli_Task.rst +++ b/es/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/es/api/Phalcon_Config.rst b/es/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/es/api/Phalcon_Config.rst +++ b/es/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/es/api/Phalcon_Config_Adapter_Ini.rst b/es/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/es/api/Phalcon_Config_Adapter_Ini.rst +++ b/es/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/es/api/Phalcon_Config_Adapter_Json.rst b/es/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/es/api/Phalcon_Config_Adapter_Json.rst +++ b/es/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/es/api/Phalcon_Config_Adapter_Php.rst b/es/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/es/api/Phalcon_Config_Adapter_Php.rst +++ b/es/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/es/api/Phalcon_Config_Adapter_Yaml.rst b/es/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/es/api/Phalcon_Config_Adapter_Yaml.rst +++ b/es/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/es/api/Phalcon_Crypt.rst b/es/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/es/api/Phalcon_Crypt.rst +++ b/es/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/es/api/Phalcon_Db.rst b/es/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/es/api/Phalcon_Db.rst +++ b/es/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/es/api/Phalcon_Db_Adapter.rst b/es/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/es/api/Phalcon_Db_Adapter.rst +++ b/es/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/es/api/Phalcon_Db_Adapter_Pdo.rst b/es/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/es/api/Phalcon_Db_Adapter_Pdo.rst +++ b/es/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/es/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/es/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/es/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/es/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/es/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/es/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/es/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/es/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/es/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/es/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/es/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/es/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/es/api/Phalcon_Db_Column.rst b/es/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/es/api/Phalcon_Db_Column.rst +++ b/es/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/es/api/Phalcon_Db_Dialect.rst b/es/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/es/api/Phalcon_Db_Dialect.rst +++ b/es/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/es/api/Phalcon_Db_Dialect_Mysql.rst b/es/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/es/api/Phalcon_Db_Dialect_Mysql.rst +++ b/es/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/es/api/Phalcon_Db_Dialect_Postgresql.rst b/es/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/es/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/es/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/es/api/Phalcon_Db_Dialect_Sqlite.rst b/es/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/es/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/es/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/es/api/Phalcon_Db_Index.rst b/es/api/Phalcon_Db_Index.rst index 227b766ccbe8..415a456a64bd 100644 --- a/es/api/Phalcon_Db_Index.rst +++ b/es/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods diff --git a/es/api/Phalcon_Db_Profiler.rst b/es/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/es/api/Phalcon_Db_Profiler.rst +++ b/es/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/es/api/Phalcon_Db_RawValue.rst b/es/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/es/api/Phalcon_Db_RawValue.rst +++ b/es/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/es/api/Phalcon_Db_Reference.rst b/es/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/es/api/Phalcon_Db_Reference.rst +++ b/es/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/es/api/Phalcon_Db_Result_Pdo.rst b/es/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/es/api/Phalcon_Db_Result_Pdo.rst +++ b/es/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/es/api/Phalcon_Debug.rst b/es/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/es/api/Phalcon_Debug.rst +++ b/es/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/es/api/Phalcon_Debug_Dump.rst b/es/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/es/api/Phalcon_Debug_Dump.rst +++ b/es/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/es/api/Phalcon_Di.rst b/es/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/es/api/Phalcon_Di.rst +++ b/es/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/es/api/Phalcon_Di_FactoryDefault.rst b/es/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/es/api/Phalcon_Di_FactoryDefault.rst +++ b/es/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/es/api/Phalcon_Di_FactoryDefault_Cli.rst b/es/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/es/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/es/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/es/api/Phalcon_Di_Injectable.rst b/es/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/es/api/Phalcon_Di_Injectable.rst +++ b/es/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/es/api/Phalcon_Di_Service.rst b/es/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/es/api/Phalcon_Di_Service.rst +++ b/es/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/es/api/Phalcon_Dispatcher.rst b/es/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/es/api/Phalcon_Dispatcher.rst +++ b/es/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/es/api/Phalcon_Escaper.rst b/es/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/es/api/Phalcon_Escaper.rst +++ b/es/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/es/api/Phalcon_Events_Event.rst b/es/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/es/api/Phalcon_Events_Event.rst +++ b/es/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/es/api/Phalcon_Events_Manager.rst b/es/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/es/api/Phalcon_Events_Manager.rst +++ b/es/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/es/api/Phalcon_Filter.rst b/es/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/es/api/Phalcon_Filter.rst +++ b/es/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/es/api/Phalcon_Flash.rst b/es/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/es/api/Phalcon_Flash.rst +++ b/es/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/es/api/Phalcon_Flash_Direct.rst b/es/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/es/api/Phalcon_Flash_Direct.rst +++ b/es/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/es/api/Phalcon_Flash_Session.rst b/es/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/es/api/Phalcon_Flash_Session.rst +++ b/es/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/es/api/Phalcon_Forms_Element.rst b/es/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/es/api/Phalcon_Forms_Element.rst +++ b/es/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_Check.rst b/es/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/es/api/Phalcon_Forms_Element_Check.rst +++ b/es/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_Date.rst b/es/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/es/api/Phalcon_Forms_Element_Date.rst +++ b/es/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_Email.rst b/es/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/es/api/Phalcon_Forms_Element_Email.rst +++ b/es/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_File.rst b/es/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/es/api/Phalcon_Forms_Element_File.rst +++ b/es/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_Hidden.rst b/es/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/es/api/Phalcon_Forms_Element_Hidden.rst +++ b/es/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_Numeric.rst b/es/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/es/api/Phalcon_Forms_Element_Numeric.rst +++ b/es/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_Password.rst b/es/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/es/api/Phalcon_Forms_Element_Password.rst +++ b/es/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_Radio.rst b/es/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/es/api/Phalcon_Forms_Element_Radio.rst +++ b/es/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_Select.rst b/es/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/es/api/Phalcon_Forms_Element_Select.rst +++ b/es/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_Submit.rst b/es/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/es/api/Phalcon_Forms_Element_Submit.rst +++ b/es/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_Text.rst b/es/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/es/api/Phalcon_Forms_Element_Text.rst +++ b/es/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Element_TextArea.rst b/es/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/es/api/Phalcon_Forms_Element_TextArea.rst +++ b/es/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/es/api/Phalcon_Forms_Manager.rst b/es/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/es/api/Phalcon_Forms_Manager.rst +++ b/es/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/es/api/Phalcon_Http_Cookie.rst b/es/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/es/api/Phalcon_Http_Cookie.rst +++ b/es/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/es/api/Phalcon_Http_Request.rst b/es/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/es/api/Phalcon_Http_Request.rst +++ b/es/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/es/api/Phalcon_Http_Request_File.rst b/es/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/es/api/Phalcon_Http_Request_File.rst +++ b/es/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/es/api/Phalcon_Http_Response.rst b/es/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/es/api/Phalcon_Http_Response.rst +++ b/es/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/es/api/Phalcon_Http_Response_Cookies.rst b/es/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/es/api/Phalcon_Http_Response_Cookies.rst +++ b/es/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/es/api/Phalcon_Image_Adapter.rst b/es/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/es/api/Phalcon_Image_Adapter.rst +++ b/es/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/es/api/Phalcon_Image_Adapter_Gd.rst b/es/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/es/api/Phalcon_Image_Adapter_Gd.rst +++ b/es/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/es/api/Phalcon_Image_Adapter_Imagick.rst b/es/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/es/api/Phalcon_Image_Adapter_Imagick.rst +++ b/es/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/es/api/Phalcon_Loader.rst b/es/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/es/api/Phalcon_Loader.rst +++ b/es/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/es/api/Phalcon_Logger_Adapter.rst b/es/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/es/api/Phalcon_Logger_Adapter.rst +++ b/es/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/es/api/Phalcon_Logger_Adapter_File.rst b/es/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/es/api/Phalcon_Logger_Adapter_File.rst +++ b/es/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/es/api/Phalcon_Logger_Adapter_Firephp.rst b/es/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/es/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/es/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/es/api/Phalcon_Logger_Adapter_Stream.rst b/es/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/es/api/Phalcon_Logger_Adapter_Stream.rst +++ b/es/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/es/api/Phalcon_Logger_Adapter_Syslog.rst b/es/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/es/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/es/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/es/api/Phalcon_Mvc_Application.rst b/es/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/es/api/Phalcon_Mvc_Application.rst +++ b/es/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/es/api/Phalcon_Mvc_Collection.rst b/es/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/es/api/Phalcon_Mvc_Collection.rst +++ b/es/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/es/api/Phalcon_Mvc_Collection_Behavior.rst b/es/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/es/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/es/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/es/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/es/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/es/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/es/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/es/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/es/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/es/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/es/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/es/api/Phalcon_Mvc_Collection_Document.rst b/es/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/es/api/Phalcon_Mvc_Collection_Document.rst +++ b/es/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/es/api/Phalcon_Mvc_Collection_Manager.rst b/es/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/es/api/Phalcon_Mvc_Collection_Manager.rst +++ b/es/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/es/api/Phalcon_Mvc_Controller.rst b/es/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/es/api/Phalcon_Mvc_Controller.rst +++ b/es/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/es/api/Phalcon_Mvc_Dispatcher.rst b/es/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/es/api/Phalcon_Mvc_Dispatcher.rst +++ b/es/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/es/api/Phalcon_Mvc_Micro.rst b/es/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/es/api/Phalcon_Mvc_Micro.rst +++ b/es/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/es/api/Phalcon_Mvc_Model.rst b/es/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/es/api/Phalcon_Mvc_Model.rst +++ b/es/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/es/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/es/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/es/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/es/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/es/api/Phalcon_Mvc_Model_Criteria.rst b/es/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/es/api/Phalcon_Mvc_Model_Criteria.rst +++ b/es/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/es/api/Phalcon_Mvc_Model_Manager.rst b/es/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/es/api/Phalcon_Mvc_Model_Manager.rst +++ b/es/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/es/api/Phalcon_Mvc_Model_Message.rst b/es/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/es/api/Phalcon_Mvc_Model_Message.rst +++ b/es/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/es/api/Phalcon_Mvc_Model_MetaData.rst b/es/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/es/api/Phalcon_Mvc_Model_MetaData.rst +++ b/es/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/es/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/es/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/es/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/es/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/es/api/Phalcon_Mvc_Model_MetaData_Files.rst b/es/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/es/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/es/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/es/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/es/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/es/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/es/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/es/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/es/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/es/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/es/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/es/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/es/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/es/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/es/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/es/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/es/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/es/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/es/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/es/api/Phalcon_Mvc_Model_MetaData_Session.rst b/es/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/es/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/es/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/es/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/es/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/es/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/es/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/es/api/Phalcon_Mvc_Model_Query.rst b/es/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/es/api/Phalcon_Mvc_Model_Query.rst +++ b/es/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/es/api/Phalcon_Mvc_Model_Query_Builder.rst b/es/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/es/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/es/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/es/api/Phalcon_Mvc_Model_Query_Lang.rst b/es/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/es/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/es/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/es/api/Phalcon_Mvc_Model_Relation.rst b/es/api/Phalcon_Mvc_Model_Relation.rst index bbd49acbd3ac..7a0c5587b554 100644 --- a/es/api/Phalcon_Mvc_Model_Relation.rst +++ b/es/api/Phalcon_Mvc_Model_Relation.rst @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned diff --git a/es/api/Phalcon_Mvc_Model_Resultset.rst b/es/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/es/api/Phalcon_Mvc_Model_Resultset.rst +++ b/es/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/es/api/Phalcon_Mvc_Model_Transaction.rst b/es/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/es/api/Phalcon_Mvc_Model_Transaction.rst +++ b/es/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/es/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/es/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/es/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/es/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/es/api/Phalcon_Mvc_Model_ValidationFailed.rst b/es/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/es/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/es/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/es/api/Phalcon_Mvc_Model_Validator.rst b/es/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/es/api/Phalcon_Mvc_Model_Validator.rst +++ b/es/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/es/api/Phalcon_Mvc_Model_Validator_Email.rst b/es/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/es/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/es/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/es/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/es/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/es/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/es/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/es/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/es/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/es/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/es/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/es/api/Phalcon_Mvc_Model_Validator_Ip.rst b/es/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/es/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/es/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/es/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/es/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/es/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/es/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/es/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/es/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/es/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/es/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/es/api/Phalcon_Mvc_Model_Validator_Regex.rst b/es/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/es/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/es/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/es/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/es/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/es/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/es/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/es/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/es/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/es/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/es/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/es/api/Phalcon_Mvc_Model_Validator_Url.rst b/es/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/es/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/es/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/es/api/Phalcon_Mvc_Router.rst b/es/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/es/api/Phalcon_Mvc_Router.rst +++ b/es/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/es/api/Phalcon_Mvc_Router_Annotations.rst b/es/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/es/api/Phalcon_Mvc_Router_Annotations.rst +++ b/es/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/es/api/Phalcon_Mvc_Router_Group.rst b/es/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/es/api/Phalcon_Mvc_Router_Group.rst +++ b/es/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/es/api/Phalcon_Mvc_Router_Route.rst b/es/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/es/api/Phalcon_Mvc_Router_Route.rst +++ b/es/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/es/api/Phalcon_Mvc_Url.rst b/es/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/es/api/Phalcon_Mvc_Url.rst +++ b/es/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/es/api/Phalcon_Mvc_View.rst b/es/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/es/api/Phalcon_Mvc_View.rst +++ b/es/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/es/api/Phalcon_Mvc_View_Engine.rst b/es/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/es/api/Phalcon_Mvc_View_Engine.rst +++ b/es/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/es/api/Phalcon_Mvc_View_Engine_Php.rst b/es/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/es/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/es/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/es/api/Phalcon_Mvc_View_Engine_Volt.rst b/es/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/es/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/es/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/es/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/es/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/es/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/es/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/es/api/Phalcon_Mvc_View_Simple.rst b/es/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/es/api/Phalcon_Mvc_View_Simple.rst +++ b/es/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/es/api/Phalcon_Paginator_Adapter.rst b/es/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/es/api/Phalcon_Paginator_Adapter.rst +++ b/es/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/es/api/Phalcon_Paginator_Adapter_Model.rst b/es/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/es/api/Phalcon_Paginator_Adapter_Model.rst +++ b/es/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/es/api/Phalcon_Paginator_Adapter_NativeArray.rst b/es/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/es/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/es/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/es/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/es/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/es/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/es/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/es/api/Phalcon_Queue_Beanstalk.rst b/es/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/es/api/Phalcon_Queue_Beanstalk.rst +++ b/es/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/es/api/Phalcon_Queue_Beanstalk_Job.rst b/es/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/es/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/es/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/es/api/Phalcon_Registry.rst b/es/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/es/api/Phalcon_Registry.rst +++ b/es/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/es/api/Phalcon_Security.rst b/es/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/es/api/Phalcon_Security.rst +++ b/es/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/es/api/Phalcon_Security_Random.rst b/es/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/es/api/Phalcon_Security_Random.rst +++ b/es/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/es/api/Phalcon_Session_Adapter.rst b/es/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/es/api/Phalcon_Session_Adapter.rst +++ b/es/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/es/api/Phalcon_Session_Adapter_Files.rst b/es/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/es/api/Phalcon_Session_Adapter_Files.rst +++ b/es/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/es/api/Phalcon_Session_Adapter_Libmemcached.rst b/es/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/es/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/es/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/es/api/Phalcon_Session_Adapter_Memcache.rst b/es/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/es/api/Phalcon_Session_Adapter_Memcache.rst +++ b/es/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/es/api/Phalcon_Session_Adapter_Redis.rst b/es/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/es/api/Phalcon_Session_Adapter_Redis.rst +++ b/es/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/es/api/Phalcon_Session_Bag.rst b/es/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/es/api/Phalcon_Session_Bag.rst +++ b/es/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/es/api/Phalcon_Tag.rst b/es/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/es/api/Phalcon_Tag.rst +++ b/es/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/es/api/Phalcon_Translate_Adapter_Gettext.rst b/es/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/es/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/es/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/es/api/Phalcon_Validation.rst b/es/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/es/api/Phalcon_Validation.rst +++ b/es/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/es/api/Phalcon_Validation_CombinedFieldsValidator.rst b/es/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/es/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/es/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Message.rst b/es/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/es/api/Phalcon_Validation_Message.rst +++ b/es/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/es/api/Phalcon_Validation_Message_Group.rst b/es/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/es/api/Phalcon_Validation_Message_Group.rst +++ b/es/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/es/api/Phalcon_Validation_Validator.rst b/es/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/es/api/Phalcon_Validation_Validator.rst +++ b/es/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Alnum.rst b/es/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/es/api/Phalcon_Validation_Validator_Alnum.rst +++ b/es/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Alpha.rst b/es/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/es/api/Phalcon_Validation_Validator_Alpha.rst +++ b/es/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Between.rst b/es/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/es/api/Phalcon_Validation_Validator_Between.rst +++ b/es/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Confirmation.rst b/es/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/es/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/es/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_CreditCard.rst b/es/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/es/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/es/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Date.rst b/es/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/es/api/Phalcon_Validation_Validator_Date.rst +++ b/es/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Digit.rst b/es/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/es/api/Phalcon_Validation_Validator_Digit.rst +++ b/es/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Email.rst b/es/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/es/api/Phalcon_Validation_Validator_Email.rst +++ b/es/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_ExclusionIn.rst b/es/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/es/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/es/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_File.rst b/es/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/es/api/Phalcon_Validation_Validator_File.rst +++ b/es/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Identical.rst b/es/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/es/api/Phalcon_Validation_Validator_Identical.rst +++ b/es/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_InclusionIn.rst b/es/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/es/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/es/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Numericality.rst b/es/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/es/api/Phalcon_Validation_Validator_Numericality.rst +++ b/es/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_PresenceOf.rst b/es/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/es/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/es/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Regex.rst b/es/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/es/api/Phalcon_Validation_Validator_Regex.rst +++ b/es/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_StringLength.rst b/es/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/es/api/Phalcon_Validation_Validator_StringLength.rst +++ b/es/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Uniqueness.rst b/es/api/Phalcon_Validation_Validator_Uniqueness.rst index af0bde58d45d..8af5174ddfba 100644 --- a/es/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/es/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,59 +10,84 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; - Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); - In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); + $validator->add( + "username", + new UniquenessValidator() + ); - Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); - It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); @@ -106,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Validation_Validator_Url.rst b/es/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/es/api/Phalcon_Validation_Validator_Url.rst +++ b/es/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/es/api/Phalcon_Version.rst b/es/api/Phalcon_Version.rst index 4322c6cb17bb..77d94d7b0e5a 100644 --- a/es/api/Phalcon_Version.rst +++ b/es/api/Phalcon_Version.rst @@ -27,51 +27,61 @@ 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. +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. final protected static **_getSpecial** (*mixed* $special) -Translates a number to a special release If Special release = 1 this function will return ALPHA +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -Returns the active version (string) +Returns the active version (string) .. code-block:: php Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/fa/api/Phalcon_Annotations_Adapter_Apc.rst b/fa/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/fa/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/fa/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/fa/api/Phalcon_Annotations_Adapter_Files.rst b/fa/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/fa/api/Phalcon_Annotations_Adapter_Files.rst +++ b/fa/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/fa/api/Phalcon_Annotations_Adapter_Memory.rst b/fa/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/fa/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/fa/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/fa/api/Phalcon_Annotations_Adapter_Xcache.rst b/fa/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/fa/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/fa/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/fa/api/Phalcon_Annotations_Reflection.rst b/fa/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/fa/api/Phalcon_Annotations_Reflection.rst +++ b/fa/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/fa/api/Phalcon_Application.rst b/fa/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/fa/api/Phalcon_Application.rst +++ b/fa/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/fa/api/Phalcon_Assets_Filters_Cssmin.rst b/fa/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/fa/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/fa/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/fa/api/Phalcon_Assets_Filters_Jsmin.rst b/fa/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/fa/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/fa/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/fa/api/Phalcon_Assets_Inline.rst b/fa/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/fa/api/Phalcon_Assets_Inline.rst +++ b/fa/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/fa/api/Phalcon_Assets_Resource.rst b/fa/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/fa/api/Phalcon_Assets_Resource.rst +++ b/fa/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/fa/api/Phalcon_Assets_Resource_Js.rst b/fa/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/fa/api/Phalcon_Assets_Resource_Js.rst +++ b/fa/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/fa/api/Phalcon_Cache_Backend.rst b/fa/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/fa/api/Phalcon_Cache_Backend.rst +++ b/fa/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/fa/api/Phalcon_Cache_Backend_Apc.rst b/fa/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/fa/api/Phalcon_Cache_Backend_Apc.rst +++ b/fa/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/fa/api/Phalcon_Cache_Backend_File.rst b/fa/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/fa/api/Phalcon_Cache_Backend_File.rst +++ b/fa/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/fa/api/Phalcon_Cache_Backend_Libmemcached.rst b/fa/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/fa/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/fa/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/fa/api/Phalcon_Cache_Backend_Memcache.rst b/fa/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/fa/api/Phalcon_Cache_Backend_Memcache.rst +++ b/fa/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/fa/api/Phalcon_Cache_Backend_Memory.rst b/fa/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/fa/api/Phalcon_Cache_Backend_Memory.rst +++ b/fa/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/fa/api/Phalcon_Cache_Backend_Mongo.rst b/fa/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/fa/api/Phalcon_Cache_Backend_Mongo.rst +++ b/fa/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/fa/api/Phalcon_Cache_Backend_Redis.rst b/fa/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/fa/api/Phalcon_Cache_Backend_Redis.rst +++ b/fa/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/fa/api/Phalcon_Cache_Backend_Xcache.rst b/fa/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/fa/api/Phalcon_Cache_Backend_Xcache.rst +++ b/fa/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/fa/api/Phalcon_Cache_Frontend_Base64.rst b/fa/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/fa/api/Phalcon_Cache_Frontend_Base64.rst +++ b/fa/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/fa/api/Phalcon_Cache_Frontend_Data.rst b/fa/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/fa/api/Phalcon_Cache_Frontend_Data.rst +++ b/fa/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/fa/api/Phalcon_Cache_Frontend_Igbinary.rst b/fa/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/fa/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/fa/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/fa/api/Phalcon_Cache_Frontend_Json.rst b/fa/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/fa/api/Phalcon_Cache_Frontend_Json.rst +++ b/fa/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/fa/api/Phalcon_Cache_Frontend_Msgpack.rst b/fa/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/fa/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/fa/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/fa/api/Phalcon_Cache_Frontend_None.rst b/fa/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/fa/api/Phalcon_Cache_Frontend_None.rst +++ b/fa/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/fa/api/Phalcon_Cache_Frontend_Output.rst b/fa/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/fa/api/Phalcon_Cache_Frontend_Output.rst +++ b/fa/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/fa/api/Phalcon_Cache_Multiple.rst b/fa/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/fa/api/Phalcon_Cache_Multiple.rst +++ b/fa/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/fa/api/Phalcon_Cli_Console.rst b/fa/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/fa/api/Phalcon_Cli_Console.rst +++ b/fa/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/fa/api/Phalcon_Cli_Dispatcher.rst b/fa/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/fa/api/Phalcon_Cli_Dispatcher.rst +++ b/fa/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/fa/api/Phalcon_Cli_Router.rst b/fa/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/fa/api/Phalcon_Cli_Router.rst +++ b/fa/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/fa/api/Phalcon_Cli_Router_Route.rst b/fa/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/fa/api/Phalcon_Cli_Router_Route.rst +++ b/fa/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/fa/api/Phalcon_Cli_Task.rst b/fa/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/fa/api/Phalcon_Cli_Task.rst +++ b/fa/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/fa/api/Phalcon_Config.rst b/fa/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/fa/api/Phalcon_Config.rst +++ b/fa/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/fa/api/Phalcon_Config_Adapter_Ini.rst b/fa/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/fa/api/Phalcon_Config_Adapter_Ini.rst +++ b/fa/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/fa/api/Phalcon_Config_Adapter_Json.rst b/fa/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/fa/api/Phalcon_Config_Adapter_Json.rst +++ b/fa/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/fa/api/Phalcon_Config_Adapter_Php.rst b/fa/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/fa/api/Phalcon_Config_Adapter_Php.rst +++ b/fa/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/fa/api/Phalcon_Config_Adapter_Yaml.rst b/fa/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/fa/api/Phalcon_Config_Adapter_Yaml.rst +++ b/fa/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/fa/api/Phalcon_Crypt.rst b/fa/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/fa/api/Phalcon_Crypt.rst +++ b/fa/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/fa/api/Phalcon_Db.rst b/fa/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/fa/api/Phalcon_Db.rst +++ b/fa/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/fa/api/Phalcon_Db_Adapter.rst b/fa/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/fa/api/Phalcon_Db_Adapter.rst +++ b/fa/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/fa/api/Phalcon_Db_Adapter_Pdo.rst b/fa/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/fa/api/Phalcon_Db_Adapter_Pdo.rst +++ b/fa/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/fa/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/fa/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/fa/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/fa/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/fa/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/fa/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/fa/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/fa/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/fa/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/fa/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/fa/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/fa/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/fa/api/Phalcon_Db_Column.rst b/fa/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/fa/api/Phalcon_Db_Column.rst +++ b/fa/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/fa/api/Phalcon_Db_Dialect.rst b/fa/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/fa/api/Phalcon_Db_Dialect.rst +++ b/fa/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/fa/api/Phalcon_Db_Dialect_Mysql.rst b/fa/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/fa/api/Phalcon_Db_Dialect_Mysql.rst +++ b/fa/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/fa/api/Phalcon_Db_Dialect_Postgresql.rst b/fa/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/fa/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/fa/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/fa/api/Phalcon_Db_Dialect_Sqlite.rst b/fa/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/fa/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/fa/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/fa/api/Phalcon_Db_Index.rst b/fa/api/Phalcon_Db_Index.rst index 227b766ccbe8..415a456a64bd 100644 --- a/fa/api/Phalcon_Db_Index.rst +++ b/fa/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods diff --git a/fa/api/Phalcon_Db_Profiler.rst b/fa/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/fa/api/Phalcon_Db_Profiler.rst +++ b/fa/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/fa/api/Phalcon_Db_RawValue.rst b/fa/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/fa/api/Phalcon_Db_RawValue.rst +++ b/fa/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/fa/api/Phalcon_Db_Reference.rst b/fa/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/fa/api/Phalcon_Db_Reference.rst +++ b/fa/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/fa/api/Phalcon_Db_Result_Pdo.rst b/fa/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/fa/api/Phalcon_Db_Result_Pdo.rst +++ b/fa/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/fa/api/Phalcon_Debug.rst b/fa/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/fa/api/Phalcon_Debug.rst +++ b/fa/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/fa/api/Phalcon_Debug_Dump.rst b/fa/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/fa/api/Phalcon_Debug_Dump.rst +++ b/fa/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/fa/api/Phalcon_Di.rst b/fa/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/fa/api/Phalcon_Di.rst +++ b/fa/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/fa/api/Phalcon_Di_FactoryDefault.rst b/fa/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/fa/api/Phalcon_Di_FactoryDefault.rst +++ b/fa/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/fa/api/Phalcon_Di_FactoryDefault_Cli.rst b/fa/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/fa/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/fa/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/fa/api/Phalcon_Di_Injectable.rst b/fa/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/fa/api/Phalcon_Di_Injectable.rst +++ b/fa/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/fa/api/Phalcon_Di_Service.rst b/fa/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/fa/api/Phalcon_Di_Service.rst +++ b/fa/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/fa/api/Phalcon_Dispatcher.rst b/fa/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/fa/api/Phalcon_Dispatcher.rst +++ b/fa/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/fa/api/Phalcon_Escaper.rst b/fa/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/fa/api/Phalcon_Escaper.rst +++ b/fa/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/fa/api/Phalcon_Events_Event.rst b/fa/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/fa/api/Phalcon_Events_Event.rst +++ b/fa/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/fa/api/Phalcon_Events_Manager.rst b/fa/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/fa/api/Phalcon_Events_Manager.rst +++ b/fa/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/fa/api/Phalcon_Filter.rst b/fa/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/fa/api/Phalcon_Filter.rst +++ b/fa/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/fa/api/Phalcon_Flash.rst b/fa/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/fa/api/Phalcon_Flash.rst +++ b/fa/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/fa/api/Phalcon_Flash_Direct.rst b/fa/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/fa/api/Phalcon_Flash_Direct.rst +++ b/fa/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/fa/api/Phalcon_Flash_Session.rst b/fa/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/fa/api/Phalcon_Flash_Session.rst +++ b/fa/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/fa/api/Phalcon_Forms_Element.rst b/fa/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/fa/api/Phalcon_Forms_Element.rst +++ b/fa/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_Check.rst b/fa/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/fa/api/Phalcon_Forms_Element_Check.rst +++ b/fa/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_Date.rst b/fa/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/fa/api/Phalcon_Forms_Element_Date.rst +++ b/fa/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_Email.rst b/fa/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/fa/api/Phalcon_Forms_Element_Email.rst +++ b/fa/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_File.rst b/fa/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/fa/api/Phalcon_Forms_Element_File.rst +++ b/fa/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_Hidden.rst b/fa/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/fa/api/Phalcon_Forms_Element_Hidden.rst +++ b/fa/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_Numeric.rst b/fa/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/fa/api/Phalcon_Forms_Element_Numeric.rst +++ b/fa/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_Password.rst b/fa/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/fa/api/Phalcon_Forms_Element_Password.rst +++ b/fa/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_Radio.rst b/fa/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/fa/api/Phalcon_Forms_Element_Radio.rst +++ b/fa/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_Select.rst b/fa/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/fa/api/Phalcon_Forms_Element_Select.rst +++ b/fa/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_Submit.rst b/fa/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/fa/api/Phalcon_Forms_Element_Submit.rst +++ b/fa/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_Text.rst b/fa/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/fa/api/Phalcon_Forms_Element_Text.rst +++ b/fa/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Element_TextArea.rst b/fa/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/fa/api/Phalcon_Forms_Element_TextArea.rst +++ b/fa/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fa/api/Phalcon_Forms_Manager.rst b/fa/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/fa/api/Phalcon_Forms_Manager.rst +++ b/fa/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/fa/api/Phalcon_Http_Cookie.rst b/fa/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/fa/api/Phalcon_Http_Cookie.rst +++ b/fa/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/fa/api/Phalcon_Http_Request.rst b/fa/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/fa/api/Phalcon_Http_Request.rst +++ b/fa/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/fa/api/Phalcon_Http_Request_File.rst b/fa/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/fa/api/Phalcon_Http_Request_File.rst +++ b/fa/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/fa/api/Phalcon_Http_Response.rst b/fa/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/fa/api/Phalcon_Http_Response.rst +++ b/fa/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/fa/api/Phalcon_Http_Response_Cookies.rst b/fa/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/fa/api/Phalcon_Http_Response_Cookies.rst +++ b/fa/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/fa/api/Phalcon_Image_Adapter.rst b/fa/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/fa/api/Phalcon_Image_Adapter.rst +++ b/fa/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/fa/api/Phalcon_Image_Adapter_Gd.rst b/fa/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/fa/api/Phalcon_Image_Adapter_Gd.rst +++ b/fa/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/fa/api/Phalcon_Image_Adapter_Imagick.rst b/fa/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/fa/api/Phalcon_Image_Adapter_Imagick.rst +++ b/fa/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/fa/api/Phalcon_Loader.rst b/fa/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/fa/api/Phalcon_Loader.rst +++ b/fa/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/fa/api/Phalcon_Logger_Adapter.rst b/fa/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/fa/api/Phalcon_Logger_Adapter.rst +++ b/fa/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/fa/api/Phalcon_Logger_Adapter_File.rst b/fa/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/fa/api/Phalcon_Logger_Adapter_File.rst +++ b/fa/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/fa/api/Phalcon_Logger_Adapter_Firephp.rst b/fa/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/fa/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/fa/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/fa/api/Phalcon_Logger_Adapter_Stream.rst b/fa/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/fa/api/Phalcon_Logger_Adapter_Stream.rst +++ b/fa/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/fa/api/Phalcon_Logger_Adapter_Syslog.rst b/fa/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/fa/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/fa/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/fa/api/Phalcon_Mvc_Application.rst b/fa/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/fa/api/Phalcon_Mvc_Application.rst +++ b/fa/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/fa/api/Phalcon_Mvc_Collection.rst b/fa/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/fa/api/Phalcon_Mvc_Collection.rst +++ b/fa/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/fa/api/Phalcon_Mvc_Collection_Behavior.rst b/fa/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/fa/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/fa/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/fa/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/fa/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/fa/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/fa/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/fa/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/fa/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/fa/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/fa/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/fa/api/Phalcon_Mvc_Collection_Document.rst b/fa/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/fa/api/Phalcon_Mvc_Collection_Document.rst +++ b/fa/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/fa/api/Phalcon_Mvc_Collection_Manager.rst b/fa/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/fa/api/Phalcon_Mvc_Collection_Manager.rst +++ b/fa/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/fa/api/Phalcon_Mvc_Controller.rst b/fa/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/fa/api/Phalcon_Mvc_Controller.rst +++ b/fa/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/fa/api/Phalcon_Mvc_Dispatcher.rst b/fa/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/fa/api/Phalcon_Mvc_Dispatcher.rst +++ b/fa/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/fa/api/Phalcon_Mvc_Micro.rst b/fa/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/fa/api/Phalcon_Mvc_Micro.rst +++ b/fa/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/fa/api/Phalcon_Mvc_Model.rst b/fa/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/fa/api/Phalcon_Mvc_Model.rst +++ b/fa/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/fa/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/fa/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/fa/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/fa/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/fa/api/Phalcon_Mvc_Model_Criteria.rst b/fa/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/fa/api/Phalcon_Mvc_Model_Criteria.rst +++ b/fa/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/fa/api/Phalcon_Mvc_Model_Manager.rst b/fa/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/fa/api/Phalcon_Mvc_Model_Manager.rst +++ b/fa/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/fa/api/Phalcon_Mvc_Model_Message.rst b/fa/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/fa/api/Phalcon_Mvc_Model_Message.rst +++ b/fa/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/fa/api/Phalcon_Mvc_Model_MetaData.rst b/fa/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/fa/api/Phalcon_Mvc_Model_MetaData.rst +++ b/fa/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fa/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/fa/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/fa/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/fa/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fa/api/Phalcon_Mvc_Model_MetaData_Files.rst b/fa/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/fa/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/fa/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fa/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/fa/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/fa/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/fa/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/fa/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/fa/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/fa/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/fa/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/fa/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/fa/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/fa/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/fa/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fa/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/fa/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/fa/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/fa/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/fa/api/Phalcon_Mvc_Model_MetaData_Session.rst b/fa/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/fa/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/fa/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fa/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/fa/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/fa/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/fa/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fa/api/Phalcon_Mvc_Model_Query.rst b/fa/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/fa/api/Phalcon_Mvc_Model_Query.rst +++ b/fa/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/fa/api/Phalcon_Mvc_Model_Query_Builder.rst b/fa/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/fa/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/fa/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/fa/api/Phalcon_Mvc_Model_Query_Lang.rst b/fa/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/fa/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/fa/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/fa/api/Phalcon_Mvc_Model_Relation.rst b/fa/api/Phalcon_Mvc_Model_Relation.rst index bbd49acbd3ac..7a0c5587b554 100644 --- a/fa/api/Phalcon_Mvc_Model_Relation.rst +++ b/fa/api/Phalcon_Mvc_Model_Relation.rst @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned diff --git a/fa/api/Phalcon_Mvc_Model_Resultset.rst b/fa/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/fa/api/Phalcon_Mvc_Model_Resultset.rst +++ b/fa/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/fa/api/Phalcon_Mvc_Model_Transaction.rst b/fa/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/fa/api/Phalcon_Mvc_Model_Transaction.rst +++ b/fa/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/fa/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/fa/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/fa/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/fa/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/fa/api/Phalcon_Mvc_Model_ValidationFailed.rst b/fa/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/fa/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/fa/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/fa/api/Phalcon_Mvc_Model_Validator.rst b/fa/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/fa/api/Phalcon_Mvc_Model_Validator_Email.rst b/fa/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fa/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/fa/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fa/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/fa/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fa/api/Phalcon_Mvc_Model_Validator_Ip.rst b/fa/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fa/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/fa/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fa/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/fa/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fa/api/Phalcon_Mvc_Model_Validator_Regex.rst b/fa/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/fa/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/fa/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fa/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/fa/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fa/api/Phalcon_Mvc_Model_Validator_Url.rst b/fa/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/fa/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/fa/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fa/api/Phalcon_Mvc_Router.rst b/fa/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/fa/api/Phalcon_Mvc_Router.rst +++ b/fa/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/fa/api/Phalcon_Mvc_Router_Annotations.rst b/fa/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/fa/api/Phalcon_Mvc_Router_Annotations.rst +++ b/fa/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/fa/api/Phalcon_Mvc_Router_Group.rst b/fa/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/fa/api/Phalcon_Mvc_Router_Group.rst +++ b/fa/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/fa/api/Phalcon_Mvc_Router_Route.rst b/fa/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/fa/api/Phalcon_Mvc_Router_Route.rst +++ b/fa/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/fa/api/Phalcon_Mvc_Url.rst b/fa/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/fa/api/Phalcon_Mvc_Url.rst +++ b/fa/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/fa/api/Phalcon_Mvc_View.rst b/fa/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/fa/api/Phalcon_Mvc_View.rst +++ b/fa/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/fa/api/Phalcon_Mvc_View_Engine.rst b/fa/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/fa/api/Phalcon_Mvc_View_Engine.rst +++ b/fa/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/fa/api/Phalcon_Mvc_View_Engine_Php.rst b/fa/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/fa/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/fa/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/fa/api/Phalcon_Mvc_View_Engine_Volt.rst b/fa/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/fa/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/fa/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/fa/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/fa/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/fa/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/fa/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/fa/api/Phalcon_Mvc_View_Simple.rst b/fa/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/fa/api/Phalcon_Mvc_View_Simple.rst +++ b/fa/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/fa/api/Phalcon_Paginator_Adapter.rst b/fa/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/fa/api/Phalcon_Paginator_Adapter.rst +++ b/fa/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/fa/api/Phalcon_Paginator_Adapter_Model.rst b/fa/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/fa/api/Phalcon_Paginator_Adapter_Model.rst +++ b/fa/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/fa/api/Phalcon_Paginator_Adapter_NativeArray.rst b/fa/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/fa/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/fa/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/fa/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/fa/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/fa/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/fa/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/fa/api/Phalcon_Queue_Beanstalk.rst b/fa/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/fa/api/Phalcon_Queue_Beanstalk.rst +++ b/fa/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/fa/api/Phalcon_Queue_Beanstalk_Job.rst b/fa/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/fa/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/fa/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/fa/api/Phalcon_Registry.rst b/fa/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/fa/api/Phalcon_Registry.rst +++ b/fa/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/fa/api/Phalcon_Security.rst b/fa/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/fa/api/Phalcon_Security.rst +++ b/fa/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/fa/api/Phalcon_Security_Random.rst b/fa/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/fa/api/Phalcon_Security_Random.rst +++ b/fa/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/fa/api/Phalcon_Session_Adapter.rst b/fa/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/fa/api/Phalcon_Session_Adapter.rst +++ b/fa/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/fa/api/Phalcon_Session_Adapter_Files.rst b/fa/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/fa/api/Phalcon_Session_Adapter_Files.rst +++ b/fa/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/fa/api/Phalcon_Session_Adapter_Libmemcached.rst b/fa/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/fa/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/fa/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/fa/api/Phalcon_Session_Adapter_Memcache.rst b/fa/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/fa/api/Phalcon_Session_Adapter_Memcache.rst +++ b/fa/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/fa/api/Phalcon_Session_Adapter_Redis.rst b/fa/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/fa/api/Phalcon_Session_Adapter_Redis.rst +++ b/fa/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/fa/api/Phalcon_Session_Bag.rst b/fa/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/fa/api/Phalcon_Session_Bag.rst +++ b/fa/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/fa/api/Phalcon_Tag.rst b/fa/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/fa/api/Phalcon_Tag.rst +++ b/fa/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/fa/api/Phalcon_Translate_Adapter_Gettext.rst b/fa/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/fa/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/fa/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/fa/api/Phalcon_Validation.rst b/fa/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/fa/api/Phalcon_Validation.rst +++ b/fa/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/fa/api/Phalcon_Validation_CombinedFieldsValidator.rst b/fa/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/fa/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/fa/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Message.rst b/fa/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/fa/api/Phalcon_Validation_Message.rst +++ b/fa/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/fa/api/Phalcon_Validation_Message_Group.rst b/fa/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/fa/api/Phalcon_Validation_Message_Group.rst +++ b/fa/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/fa/api/Phalcon_Validation_Validator.rst b/fa/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/fa/api/Phalcon_Validation_Validator.rst +++ b/fa/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Alnum.rst b/fa/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/fa/api/Phalcon_Validation_Validator_Alnum.rst +++ b/fa/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Alpha.rst b/fa/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/fa/api/Phalcon_Validation_Validator_Alpha.rst +++ b/fa/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Between.rst b/fa/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/fa/api/Phalcon_Validation_Validator_Between.rst +++ b/fa/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Confirmation.rst b/fa/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/fa/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/fa/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_CreditCard.rst b/fa/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/fa/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/fa/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Date.rst b/fa/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/fa/api/Phalcon_Validation_Validator_Date.rst +++ b/fa/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Digit.rst b/fa/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/fa/api/Phalcon_Validation_Validator_Digit.rst +++ b/fa/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Email.rst b/fa/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/fa/api/Phalcon_Validation_Validator_Email.rst +++ b/fa/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_ExclusionIn.rst b/fa/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/fa/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/fa/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_File.rst b/fa/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/fa/api/Phalcon_Validation_Validator_File.rst +++ b/fa/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Identical.rst b/fa/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/fa/api/Phalcon_Validation_Validator_Identical.rst +++ b/fa/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_InclusionIn.rst b/fa/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/fa/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/fa/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Numericality.rst b/fa/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/fa/api/Phalcon_Validation_Validator_Numericality.rst +++ b/fa/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_PresenceOf.rst b/fa/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/fa/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/fa/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Regex.rst b/fa/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/fa/api/Phalcon_Validation_Validator_Regex.rst +++ b/fa/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_StringLength.rst b/fa/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/fa/api/Phalcon_Validation_Validator_StringLength.rst +++ b/fa/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Uniqueness.rst b/fa/api/Phalcon_Validation_Validator_Uniqueness.rst index af0bde58d45d..8af5174ddfba 100644 --- a/fa/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/fa/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,59 +10,84 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; - Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); - In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); + $validator->add( + "username", + new UniquenessValidator() + ); - Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); - It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); @@ -106,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Validation_Validator_Url.rst b/fa/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/fa/api/Phalcon_Validation_Validator_Url.rst +++ b/fa/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fa/api/Phalcon_Version.rst b/fa/api/Phalcon_Version.rst index 4322c6cb17bb..77d94d7b0e5a 100644 --- a/fa/api/Phalcon_Version.rst +++ b/fa/api/Phalcon_Version.rst @@ -27,51 +27,61 @@ 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. +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. final protected static **_getSpecial** (*mixed* $special) -Translates a number to a special release If Special release = 1 this function will return ALPHA +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -Returns the active version (string) +Returns the active version (string) .. code-block:: php Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/fr/api/Phalcon_Annotations_Adapter_Apc.rst b/fr/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/fr/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/fr/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/fr/api/Phalcon_Annotations_Adapter_Files.rst b/fr/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/fr/api/Phalcon_Annotations_Adapter_Files.rst +++ b/fr/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/fr/api/Phalcon_Annotations_Adapter_Memory.rst b/fr/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/fr/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/fr/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/fr/api/Phalcon_Annotations_Adapter_Xcache.rst b/fr/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/fr/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/fr/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/fr/api/Phalcon_Annotations_Reflection.rst b/fr/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/fr/api/Phalcon_Annotations_Reflection.rst +++ b/fr/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/fr/api/Phalcon_Application.rst b/fr/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/fr/api/Phalcon_Application.rst +++ b/fr/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/fr/api/Phalcon_Assets_Filters_Cssmin.rst b/fr/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/fr/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/fr/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/fr/api/Phalcon_Assets_Filters_Jsmin.rst b/fr/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/fr/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/fr/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/fr/api/Phalcon_Assets_Inline.rst b/fr/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/fr/api/Phalcon_Assets_Inline.rst +++ b/fr/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/fr/api/Phalcon_Assets_Resource.rst b/fr/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/fr/api/Phalcon_Assets_Resource.rst +++ b/fr/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/fr/api/Phalcon_Assets_Resource_Js.rst b/fr/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/fr/api/Phalcon_Assets_Resource_Js.rst +++ b/fr/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/fr/api/Phalcon_Cache_Backend.rst b/fr/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/fr/api/Phalcon_Cache_Backend.rst +++ b/fr/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/fr/api/Phalcon_Cache_Backend_Apc.rst b/fr/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/fr/api/Phalcon_Cache_Backend_Apc.rst +++ b/fr/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/fr/api/Phalcon_Cache_Backend_File.rst b/fr/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/fr/api/Phalcon_Cache_Backend_File.rst +++ b/fr/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/fr/api/Phalcon_Cache_Backend_Libmemcached.rst b/fr/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/fr/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/fr/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/fr/api/Phalcon_Cache_Backend_Memcache.rst b/fr/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/fr/api/Phalcon_Cache_Backend_Memcache.rst +++ b/fr/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/fr/api/Phalcon_Cache_Backend_Memory.rst b/fr/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/fr/api/Phalcon_Cache_Backend_Memory.rst +++ b/fr/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/fr/api/Phalcon_Cache_Backend_Mongo.rst b/fr/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/fr/api/Phalcon_Cache_Backend_Mongo.rst +++ b/fr/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/fr/api/Phalcon_Cache_Backend_Redis.rst b/fr/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/fr/api/Phalcon_Cache_Backend_Redis.rst +++ b/fr/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/fr/api/Phalcon_Cache_Backend_Xcache.rst b/fr/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/fr/api/Phalcon_Cache_Backend_Xcache.rst +++ b/fr/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/fr/api/Phalcon_Cache_Frontend_Base64.rst b/fr/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/fr/api/Phalcon_Cache_Frontend_Base64.rst +++ b/fr/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/fr/api/Phalcon_Cache_Frontend_Data.rst b/fr/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/fr/api/Phalcon_Cache_Frontend_Data.rst +++ b/fr/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/fr/api/Phalcon_Cache_Frontend_Igbinary.rst b/fr/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/fr/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/fr/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/fr/api/Phalcon_Cache_Frontend_Json.rst b/fr/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/fr/api/Phalcon_Cache_Frontend_Json.rst +++ b/fr/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/fr/api/Phalcon_Cache_Frontend_Msgpack.rst b/fr/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/fr/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/fr/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/fr/api/Phalcon_Cache_Frontend_None.rst b/fr/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/fr/api/Phalcon_Cache_Frontend_None.rst +++ b/fr/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/fr/api/Phalcon_Cache_Frontend_Output.rst b/fr/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/fr/api/Phalcon_Cache_Frontend_Output.rst +++ b/fr/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/fr/api/Phalcon_Cache_Multiple.rst b/fr/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/fr/api/Phalcon_Cache_Multiple.rst +++ b/fr/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/fr/api/Phalcon_Cli_Console.rst b/fr/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/fr/api/Phalcon_Cli_Console.rst +++ b/fr/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/fr/api/Phalcon_Cli_Dispatcher.rst b/fr/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/fr/api/Phalcon_Cli_Dispatcher.rst +++ b/fr/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/fr/api/Phalcon_Cli_Router.rst b/fr/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/fr/api/Phalcon_Cli_Router.rst +++ b/fr/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/fr/api/Phalcon_Cli_Router_Route.rst b/fr/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/fr/api/Phalcon_Cli_Router_Route.rst +++ b/fr/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/fr/api/Phalcon_Cli_Task.rst b/fr/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/fr/api/Phalcon_Cli_Task.rst +++ b/fr/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/fr/api/Phalcon_Config.rst b/fr/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/fr/api/Phalcon_Config.rst +++ b/fr/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/fr/api/Phalcon_Config_Adapter_Ini.rst b/fr/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/fr/api/Phalcon_Config_Adapter_Ini.rst +++ b/fr/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/fr/api/Phalcon_Config_Adapter_Json.rst b/fr/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/fr/api/Phalcon_Config_Adapter_Json.rst +++ b/fr/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/fr/api/Phalcon_Config_Adapter_Php.rst b/fr/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/fr/api/Phalcon_Config_Adapter_Php.rst +++ b/fr/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/fr/api/Phalcon_Config_Adapter_Yaml.rst b/fr/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/fr/api/Phalcon_Config_Adapter_Yaml.rst +++ b/fr/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/fr/api/Phalcon_Crypt.rst b/fr/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/fr/api/Phalcon_Crypt.rst +++ b/fr/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/fr/api/Phalcon_Db.rst b/fr/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/fr/api/Phalcon_Db.rst +++ b/fr/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/fr/api/Phalcon_Db_Adapter.rst b/fr/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/fr/api/Phalcon_Db_Adapter.rst +++ b/fr/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/fr/api/Phalcon_Db_Adapter_Pdo.rst b/fr/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/fr/api/Phalcon_Db_Adapter_Pdo.rst +++ b/fr/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/fr/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/fr/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/fr/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/fr/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/fr/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/fr/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/fr/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/fr/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/fr/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/fr/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/fr/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/fr/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/fr/api/Phalcon_Db_Column.rst b/fr/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/fr/api/Phalcon_Db_Column.rst +++ b/fr/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/fr/api/Phalcon_Db_Dialect.rst b/fr/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/fr/api/Phalcon_Db_Dialect.rst +++ b/fr/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/fr/api/Phalcon_Db_Dialect_Mysql.rst b/fr/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/fr/api/Phalcon_Db_Dialect_Mysql.rst +++ b/fr/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/fr/api/Phalcon_Db_Dialect_Postgresql.rst b/fr/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/fr/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/fr/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/fr/api/Phalcon_Db_Dialect_Sqlite.rst b/fr/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/fr/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/fr/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/fr/api/Phalcon_Db_Index.rst b/fr/api/Phalcon_Db_Index.rst index 227b766ccbe8..415a456a64bd 100644 --- a/fr/api/Phalcon_Db_Index.rst +++ b/fr/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods diff --git a/fr/api/Phalcon_Db_Profiler.rst b/fr/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/fr/api/Phalcon_Db_Profiler.rst +++ b/fr/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/fr/api/Phalcon_Db_RawValue.rst b/fr/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/fr/api/Phalcon_Db_RawValue.rst +++ b/fr/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/fr/api/Phalcon_Db_Reference.rst b/fr/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/fr/api/Phalcon_Db_Reference.rst +++ b/fr/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/fr/api/Phalcon_Db_Result_Pdo.rst b/fr/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/fr/api/Phalcon_Db_Result_Pdo.rst +++ b/fr/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/fr/api/Phalcon_Debug.rst b/fr/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/fr/api/Phalcon_Debug.rst +++ b/fr/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/fr/api/Phalcon_Debug_Dump.rst b/fr/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/fr/api/Phalcon_Debug_Dump.rst +++ b/fr/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/fr/api/Phalcon_Di.rst b/fr/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/fr/api/Phalcon_Di.rst +++ b/fr/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/fr/api/Phalcon_Di_FactoryDefault.rst b/fr/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/fr/api/Phalcon_Di_FactoryDefault.rst +++ b/fr/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/fr/api/Phalcon_Di_FactoryDefault_Cli.rst b/fr/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/fr/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/fr/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/fr/api/Phalcon_Di_Injectable.rst b/fr/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/fr/api/Phalcon_Di_Injectable.rst +++ b/fr/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/fr/api/Phalcon_Di_Service.rst b/fr/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/fr/api/Phalcon_Di_Service.rst +++ b/fr/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/fr/api/Phalcon_Dispatcher.rst b/fr/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/fr/api/Phalcon_Dispatcher.rst +++ b/fr/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/fr/api/Phalcon_Escaper.rst b/fr/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/fr/api/Phalcon_Escaper.rst +++ b/fr/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/fr/api/Phalcon_Events_Event.rst b/fr/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/fr/api/Phalcon_Events_Event.rst +++ b/fr/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/fr/api/Phalcon_Events_Manager.rst b/fr/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/fr/api/Phalcon_Events_Manager.rst +++ b/fr/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/fr/api/Phalcon_Filter.rst b/fr/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/fr/api/Phalcon_Filter.rst +++ b/fr/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/fr/api/Phalcon_Flash.rst b/fr/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/fr/api/Phalcon_Flash.rst +++ b/fr/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/fr/api/Phalcon_Flash_Direct.rst b/fr/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/fr/api/Phalcon_Flash_Direct.rst +++ b/fr/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/fr/api/Phalcon_Flash_Session.rst b/fr/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/fr/api/Phalcon_Flash_Session.rst +++ b/fr/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/fr/api/Phalcon_Forms_Element.rst b/fr/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/fr/api/Phalcon_Forms_Element.rst +++ b/fr/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_Check.rst b/fr/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/fr/api/Phalcon_Forms_Element_Check.rst +++ b/fr/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_Date.rst b/fr/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/fr/api/Phalcon_Forms_Element_Date.rst +++ b/fr/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_Email.rst b/fr/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/fr/api/Phalcon_Forms_Element_Email.rst +++ b/fr/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_File.rst b/fr/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/fr/api/Phalcon_Forms_Element_File.rst +++ b/fr/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_Hidden.rst b/fr/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/fr/api/Phalcon_Forms_Element_Hidden.rst +++ b/fr/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_Numeric.rst b/fr/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/fr/api/Phalcon_Forms_Element_Numeric.rst +++ b/fr/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_Password.rst b/fr/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/fr/api/Phalcon_Forms_Element_Password.rst +++ b/fr/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_Radio.rst b/fr/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/fr/api/Phalcon_Forms_Element_Radio.rst +++ b/fr/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_Select.rst b/fr/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/fr/api/Phalcon_Forms_Element_Select.rst +++ b/fr/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_Submit.rst b/fr/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/fr/api/Phalcon_Forms_Element_Submit.rst +++ b/fr/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_Text.rst b/fr/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/fr/api/Phalcon_Forms_Element_Text.rst +++ b/fr/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Element_TextArea.rst b/fr/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/fr/api/Phalcon_Forms_Element_TextArea.rst +++ b/fr/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/fr/api/Phalcon_Forms_Manager.rst b/fr/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/fr/api/Phalcon_Forms_Manager.rst +++ b/fr/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/fr/api/Phalcon_Http_Cookie.rst b/fr/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/fr/api/Phalcon_Http_Cookie.rst +++ b/fr/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/fr/api/Phalcon_Http_Request.rst b/fr/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/fr/api/Phalcon_Http_Request.rst +++ b/fr/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/fr/api/Phalcon_Http_Request_File.rst b/fr/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/fr/api/Phalcon_Http_Request_File.rst +++ b/fr/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/fr/api/Phalcon_Http_Response.rst b/fr/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/fr/api/Phalcon_Http_Response.rst +++ b/fr/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/fr/api/Phalcon_Http_Response_Cookies.rst b/fr/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/fr/api/Phalcon_Http_Response_Cookies.rst +++ b/fr/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/fr/api/Phalcon_Image_Adapter.rst b/fr/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/fr/api/Phalcon_Image_Adapter.rst +++ b/fr/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/fr/api/Phalcon_Image_Adapter_Gd.rst b/fr/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/fr/api/Phalcon_Image_Adapter_Gd.rst +++ b/fr/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/fr/api/Phalcon_Image_Adapter_Imagick.rst b/fr/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/fr/api/Phalcon_Image_Adapter_Imagick.rst +++ b/fr/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/fr/api/Phalcon_Loader.rst b/fr/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/fr/api/Phalcon_Loader.rst +++ b/fr/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/fr/api/Phalcon_Logger_Adapter.rst b/fr/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/fr/api/Phalcon_Logger_Adapter.rst +++ b/fr/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/fr/api/Phalcon_Logger_Adapter_File.rst b/fr/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/fr/api/Phalcon_Logger_Adapter_File.rst +++ b/fr/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/fr/api/Phalcon_Logger_Adapter_Firephp.rst b/fr/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/fr/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/fr/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/fr/api/Phalcon_Logger_Adapter_Stream.rst b/fr/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/fr/api/Phalcon_Logger_Adapter_Stream.rst +++ b/fr/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/fr/api/Phalcon_Logger_Adapter_Syslog.rst b/fr/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/fr/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/fr/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/fr/api/Phalcon_Mvc_Application.rst b/fr/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/fr/api/Phalcon_Mvc_Application.rst +++ b/fr/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/fr/api/Phalcon_Mvc_Collection.rst b/fr/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/fr/api/Phalcon_Mvc_Collection.rst +++ b/fr/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/fr/api/Phalcon_Mvc_Collection_Behavior.rst b/fr/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/fr/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/fr/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/fr/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/fr/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/fr/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/fr/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/fr/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/fr/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/fr/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/fr/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/fr/api/Phalcon_Mvc_Collection_Document.rst b/fr/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/fr/api/Phalcon_Mvc_Collection_Document.rst +++ b/fr/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/fr/api/Phalcon_Mvc_Collection_Manager.rst b/fr/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/fr/api/Phalcon_Mvc_Collection_Manager.rst +++ b/fr/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/fr/api/Phalcon_Mvc_Controller.rst b/fr/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/fr/api/Phalcon_Mvc_Controller.rst +++ b/fr/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/fr/api/Phalcon_Mvc_Dispatcher.rst b/fr/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/fr/api/Phalcon_Mvc_Dispatcher.rst +++ b/fr/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/fr/api/Phalcon_Mvc_Micro.rst b/fr/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/fr/api/Phalcon_Mvc_Micro.rst +++ b/fr/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/fr/api/Phalcon_Mvc_Model.rst b/fr/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/fr/api/Phalcon_Mvc_Model.rst +++ b/fr/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/fr/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/fr/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/fr/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/fr/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/fr/api/Phalcon_Mvc_Model_Criteria.rst b/fr/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/fr/api/Phalcon_Mvc_Model_Criteria.rst +++ b/fr/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/fr/api/Phalcon_Mvc_Model_Manager.rst b/fr/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/fr/api/Phalcon_Mvc_Model_Manager.rst +++ b/fr/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/fr/api/Phalcon_Mvc_Model_Message.rst b/fr/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/fr/api/Phalcon_Mvc_Model_Message.rst +++ b/fr/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/fr/api/Phalcon_Mvc_Model_MetaData.rst b/fr/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/fr/api/Phalcon_Mvc_Model_MetaData.rst +++ b/fr/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fr/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/fr/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/fr/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/fr/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fr/api/Phalcon_Mvc_Model_MetaData_Files.rst b/fr/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/fr/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/fr/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fr/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/fr/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/fr/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/fr/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/fr/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/fr/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/fr/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/fr/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/fr/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/fr/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/fr/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/fr/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fr/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/fr/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/fr/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/fr/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/fr/api/Phalcon_Mvc_Model_MetaData_Session.rst b/fr/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/fr/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/fr/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fr/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/fr/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/fr/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/fr/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/fr/api/Phalcon_Mvc_Model_Query.rst b/fr/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/fr/api/Phalcon_Mvc_Model_Query.rst +++ b/fr/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/fr/api/Phalcon_Mvc_Model_Query_Builder.rst b/fr/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/fr/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/fr/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/fr/api/Phalcon_Mvc_Model_Query_Lang.rst b/fr/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/fr/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/fr/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/fr/api/Phalcon_Mvc_Model_Relation.rst b/fr/api/Phalcon_Mvc_Model_Relation.rst index 933ca9255164..7a0c5587b554 100644 --- a/fr/api/Phalcon_Mvc_Model_Relation.rst +++ b/fr/api/Phalcon_Mvc_Model_Relation.rst @@ -41,7 +41,7 @@ Phalcon\\Mvc\\Model\\Relation constructor public **setIntermediateRelation** (*string* | *array* $intermediateFields, *string* $intermediateModel, *string* $intermediateReferencedFields) -Sets the intermediate model data for has-\*-through relations +Sets the intermediate model data for has-*-through relations @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned @@ -113,16 +114,19 @@ Check if records returned by getting belongs-to/has-many are implicitly cached d public *string* | *array* **getIntermediateFields** () -Gets the intermediate fields for has-\*-through relations +Gets the intermediate fields for has-*-through relations public **getIntermediateModel** () -Gets the intermediate model for has-\*-through relations +Gets the intermediate model for has-*-through relations public *string* | *array* **getIntermediateReferencedFields** () -Gets the intermediate referenced fields for has-\*-through relations +Gets the intermediate referenced fields for has-*-through relations + + + diff --git a/fr/api/Phalcon_Mvc_Model_Resultset.rst b/fr/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/fr/api/Phalcon_Mvc_Model_Resultset.rst +++ b/fr/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/fr/api/Phalcon_Mvc_Model_Transaction.rst b/fr/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/fr/api/Phalcon_Mvc_Model_Transaction.rst +++ b/fr/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/fr/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/fr/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/fr/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/fr/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/fr/api/Phalcon_Mvc_Model_ValidationFailed.rst b/fr/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/fr/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/fr/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/fr/api/Phalcon_Mvc_Model_Validator.rst b/fr/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/fr/api/Phalcon_Mvc_Model_Validator_Email.rst b/fr/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fr/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/fr/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fr/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/fr/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fr/api/Phalcon_Mvc_Model_Validator_Ip.rst b/fr/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fr/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/fr/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fr/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/fr/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fr/api/Phalcon_Mvc_Model_Validator_Regex.rst b/fr/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/fr/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/fr/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fr/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/fr/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fr/api/Phalcon_Mvc_Model_Validator_Url.rst b/fr/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/fr/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/fr/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/fr/api/Phalcon_Mvc_Router.rst b/fr/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/fr/api/Phalcon_Mvc_Router.rst +++ b/fr/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/fr/api/Phalcon_Mvc_Router_Annotations.rst b/fr/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/fr/api/Phalcon_Mvc_Router_Annotations.rst +++ b/fr/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/fr/api/Phalcon_Mvc_Router_Group.rst b/fr/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/fr/api/Phalcon_Mvc_Router_Group.rst +++ b/fr/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/fr/api/Phalcon_Mvc_Router_Route.rst b/fr/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/fr/api/Phalcon_Mvc_Router_Route.rst +++ b/fr/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/fr/api/Phalcon_Mvc_Url.rst b/fr/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/fr/api/Phalcon_Mvc_Url.rst +++ b/fr/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/fr/api/Phalcon_Mvc_View.rst b/fr/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/fr/api/Phalcon_Mvc_View.rst +++ b/fr/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/fr/api/Phalcon_Mvc_View_Engine.rst b/fr/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/fr/api/Phalcon_Mvc_View_Engine.rst +++ b/fr/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/fr/api/Phalcon_Mvc_View_Engine_Php.rst b/fr/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/fr/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/fr/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/fr/api/Phalcon_Mvc_View_Engine_Volt.rst b/fr/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/fr/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/fr/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/fr/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/fr/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/fr/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/fr/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/fr/api/Phalcon_Mvc_View_Simple.rst b/fr/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/fr/api/Phalcon_Mvc_View_Simple.rst +++ b/fr/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/fr/api/Phalcon_Paginator_Adapter.rst b/fr/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/fr/api/Phalcon_Paginator_Adapter.rst +++ b/fr/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/fr/api/Phalcon_Paginator_Adapter_Model.rst b/fr/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/fr/api/Phalcon_Paginator_Adapter_Model.rst +++ b/fr/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/fr/api/Phalcon_Paginator_Adapter_NativeArray.rst b/fr/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/fr/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/fr/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/fr/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/fr/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/fr/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/fr/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/fr/api/Phalcon_Queue_Beanstalk.rst b/fr/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/fr/api/Phalcon_Queue_Beanstalk.rst +++ b/fr/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/fr/api/Phalcon_Queue_Beanstalk_Job.rst b/fr/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/fr/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/fr/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/fr/api/Phalcon_Registry.rst b/fr/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/fr/api/Phalcon_Registry.rst +++ b/fr/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/fr/api/Phalcon_Security.rst b/fr/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/fr/api/Phalcon_Security.rst +++ b/fr/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/fr/api/Phalcon_Security_Random.rst b/fr/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/fr/api/Phalcon_Security_Random.rst +++ b/fr/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/fr/api/Phalcon_Session_Adapter.rst b/fr/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/fr/api/Phalcon_Session_Adapter.rst +++ b/fr/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/fr/api/Phalcon_Session_Adapter_Files.rst b/fr/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/fr/api/Phalcon_Session_Adapter_Files.rst +++ b/fr/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/fr/api/Phalcon_Session_Adapter_Libmemcached.rst b/fr/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/fr/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/fr/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/fr/api/Phalcon_Session_Adapter_Memcache.rst b/fr/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/fr/api/Phalcon_Session_Adapter_Memcache.rst +++ b/fr/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/fr/api/Phalcon_Session_Adapter_Redis.rst b/fr/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/fr/api/Phalcon_Session_Adapter_Redis.rst +++ b/fr/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/fr/api/Phalcon_Session_Bag.rst b/fr/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/fr/api/Phalcon_Session_Bag.rst +++ b/fr/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/fr/api/Phalcon_Tag.rst b/fr/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/fr/api/Phalcon_Tag.rst +++ b/fr/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/fr/api/Phalcon_Translate_Adapter_Gettext.rst b/fr/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/fr/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/fr/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/fr/api/Phalcon_Validation.rst b/fr/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/fr/api/Phalcon_Validation.rst +++ b/fr/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/fr/api/Phalcon_Validation_CombinedFieldsValidator.rst b/fr/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/fr/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/fr/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Message.rst b/fr/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/fr/api/Phalcon_Validation_Message.rst +++ b/fr/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/fr/api/Phalcon_Validation_Message_Group.rst b/fr/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/fr/api/Phalcon_Validation_Message_Group.rst +++ b/fr/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/fr/api/Phalcon_Validation_Validator.rst b/fr/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/fr/api/Phalcon_Validation_Validator.rst +++ b/fr/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Alnum.rst b/fr/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/fr/api/Phalcon_Validation_Validator_Alnum.rst +++ b/fr/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Alpha.rst b/fr/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/fr/api/Phalcon_Validation_Validator_Alpha.rst +++ b/fr/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Between.rst b/fr/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/fr/api/Phalcon_Validation_Validator_Between.rst +++ b/fr/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Confirmation.rst b/fr/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/fr/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/fr/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_CreditCard.rst b/fr/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/fr/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/fr/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Date.rst b/fr/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/fr/api/Phalcon_Validation_Validator_Date.rst +++ b/fr/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Digit.rst b/fr/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/fr/api/Phalcon_Validation_Validator_Digit.rst +++ b/fr/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Email.rst b/fr/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/fr/api/Phalcon_Validation_Validator_Email.rst +++ b/fr/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_ExclusionIn.rst b/fr/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/fr/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/fr/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_File.rst b/fr/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/fr/api/Phalcon_Validation_Validator_File.rst +++ b/fr/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Identical.rst b/fr/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/fr/api/Phalcon_Validation_Validator_Identical.rst +++ b/fr/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_InclusionIn.rst b/fr/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/fr/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/fr/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Numericality.rst b/fr/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/fr/api/Phalcon_Validation_Validator_Numericality.rst +++ b/fr/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_PresenceOf.rst b/fr/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/fr/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/fr/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Regex.rst b/fr/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/fr/api/Phalcon_Validation_Validator_Regex.rst +++ b/fr/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_StringLength.rst b/fr/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/fr/api/Phalcon_Validation_Validator_StringLength.rst +++ b/fr/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Uniqueness.rst b/fr/api/Phalcon_Validation_Validator_Uniqueness.rst index af0bde58d45d..8af5174ddfba 100644 --- a/fr/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/fr/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,59 +10,84 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; - Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); - In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); + $validator->add( + "username", + new UniquenessValidator() + ); - Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); - It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); @@ -106,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Validation_Validator_Url.rst b/fr/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/fr/api/Phalcon_Validation_Validator_Url.rst +++ b/fr/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/fr/api/Phalcon_Version.rst b/fr/api/Phalcon_Version.rst index 4322c6cb17bb..77d94d7b0e5a 100644 --- a/fr/api/Phalcon_Version.rst +++ b/fr/api/Phalcon_Version.rst @@ -27,51 +27,61 @@ 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. +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. final protected static **_getSpecial** (*mixed* $special) -Translates a number to a special release If Special release = 1 this function will return ALPHA +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -Returns the active version (string) +Returns the active version (string) .. code-block:: php Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/id/api/Phalcon_Annotations_Adapter_Apc.rst b/id/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/id/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/id/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/id/api/Phalcon_Annotations_Adapter_Files.rst b/id/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/id/api/Phalcon_Annotations_Adapter_Files.rst +++ b/id/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/id/api/Phalcon_Annotations_Adapter_Memory.rst b/id/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/id/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/id/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/id/api/Phalcon_Annotations_Adapter_Xcache.rst b/id/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/id/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/id/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/id/api/Phalcon_Annotations_Reflection.rst b/id/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/id/api/Phalcon_Annotations_Reflection.rst +++ b/id/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/id/api/Phalcon_Application.rst b/id/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/id/api/Phalcon_Application.rst +++ b/id/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/id/api/Phalcon_Assets_Filters_Cssmin.rst b/id/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/id/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/id/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/id/api/Phalcon_Assets_Filters_Jsmin.rst b/id/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/id/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/id/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/id/api/Phalcon_Assets_Inline.rst b/id/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/id/api/Phalcon_Assets_Inline.rst +++ b/id/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/id/api/Phalcon_Assets_Resource.rst b/id/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/id/api/Phalcon_Assets_Resource.rst +++ b/id/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/id/api/Phalcon_Assets_Resource_Js.rst b/id/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/id/api/Phalcon_Assets_Resource_Js.rst +++ b/id/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/id/api/Phalcon_Cache_Backend.rst b/id/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/id/api/Phalcon_Cache_Backend.rst +++ b/id/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/id/api/Phalcon_Cache_Backend_Apc.rst b/id/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/id/api/Phalcon_Cache_Backend_Apc.rst +++ b/id/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/id/api/Phalcon_Cache_Backend_File.rst b/id/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/id/api/Phalcon_Cache_Backend_File.rst +++ b/id/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/id/api/Phalcon_Cache_Backend_Libmemcached.rst b/id/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/id/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/id/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/id/api/Phalcon_Cache_Backend_Memcache.rst b/id/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/id/api/Phalcon_Cache_Backend_Memcache.rst +++ b/id/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/id/api/Phalcon_Cache_Backend_Memory.rst b/id/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/id/api/Phalcon_Cache_Backend_Memory.rst +++ b/id/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/id/api/Phalcon_Cache_Backend_Mongo.rst b/id/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/id/api/Phalcon_Cache_Backend_Mongo.rst +++ b/id/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/id/api/Phalcon_Cache_Backend_Redis.rst b/id/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/id/api/Phalcon_Cache_Backend_Redis.rst +++ b/id/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/id/api/Phalcon_Cache_Backend_Xcache.rst b/id/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/id/api/Phalcon_Cache_Backend_Xcache.rst +++ b/id/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/id/api/Phalcon_Cache_Frontend_Base64.rst b/id/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/id/api/Phalcon_Cache_Frontend_Base64.rst +++ b/id/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/id/api/Phalcon_Cache_Frontend_Data.rst b/id/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/id/api/Phalcon_Cache_Frontend_Data.rst +++ b/id/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/id/api/Phalcon_Cache_Frontend_Igbinary.rst b/id/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/id/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/id/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/id/api/Phalcon_Cache_Frontend_Json.rst b/id/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/id/api/Phalcon_Cache_Frontend_Json.rst +++ b/id/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/id/api/Phalcon_Cache_Frontend_Msgpack.rst b/id/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/id/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/id/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/id/api/Phalcon_Cache_Frontend_None.rst b/id/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/id/api/Phalcon_Cache_Frontend_None.rst +++ b/id/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/id/api/Phalcon_Cache_Frontend_Output.rst b/id/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/id/api/Phalcon_Cache_Frontend_Output.rst +++ b/id/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/id/api/Phalcon_Cache_Multiple.rst b/id/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/id/api/Phalcon_Cache_Multiple.rst +++ b/id/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/id/api/Phalcon_Cli_Console.rst b/id/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/id/api/Phalcon_Cli_Console.rst +++ b/id/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/id/api/Phalcon_Cli_Dispatcher.rst b/id/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/id/api/Phalcon_Cli_Dispatcher.rst +++ b/id/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/id/api/Phalcon_Cli_Router.rst b/id/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/id/api/Phalcon_Cli_Router.rst +++ b/id/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/id/api/Phalcon_Cli_Router_Route.rst b/id/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/id/api/Phalcon_Cli_Router_Route.rst +++ b/id/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/id/api/Phalcon_Cli_Task.rst b/id/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/id/api/Phalcon_Cli_Task.rst +++ b/id/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/id/api/Phalcon_Config.rst b/id/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/id/api/Phalcon_Config.rst +++ b/id/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/id/api/Phalcon_Config_Adapter_Ini.rst b/id/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/id/api/Phalcon_Config_Adapter_Ini.rst +++ b/id/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/id/api/Phalcon_Config_Adapter_Json.rst b/id/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/id/api/Phalcon_Config_Adapter_Json.rst +++ b/id/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/id/api/Phalcon_Config_Adapter_Php.rst b/id/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/id/api/Phalcon_Config_Adapter_Php.rst +++ b/id/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/id/api/Phalcon_Config_Adapter_Yaml.rst b/id/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/id/api/Phalcon_Config_Adapter_Yaml.rst +++ b/id/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/id/api/Phalcon_Crypt.rst b/id/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/id/api/Phalcon_Crypt.rst +++ b/id/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/id/api/Phalcon_Db.rst b/id/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/id/api/Phalcon_Db.rst +++ b/id/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/id/api/Phalcon_Db_Adapter.rst b/id/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/id/api/Phalcon_Db_Adapter.rst +++ b/id/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/id/api/Phalcon_Db_Adapter_Pdo.rst b/id/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/id/api/Phalcon_Db_Adapter_Pdo.rst +++ b/id/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/id/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/id/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/id/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/id/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/id/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/id/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/id/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/id/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/id/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/id/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/id/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/id/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/id/api/Phalcon_Db_Column.rst b/id/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/id/api/Phalcon_Db_Column.rst +++ b/id/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/id/api/Phalcon_Db_Dialect.rst b/id/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/id/api/Phalcon_Db_Dialect.rst +++ b/id/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/id/api/Phalcon_Db_Dialect_Mysql.rst b/id/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/id/api/Phalcon_Db_Dialect_Mysql.rst +++ b/id/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/id/api/Phalcon_Db_Dialect_Postgresql.rst b/id/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/id/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/id/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/id/api/Phalcon_Db_Dialect_Sqlite.rst b/id/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/id/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/id/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/id/api/Phalcon_Db_Index.rst b/id/api/Phalcon_Db_Index.rst index 227b766ccbe8..415a456a64bd 100644 --- a/id/api/Phalcon_Db_Index.rst +++ b/id/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods diff --git a/id/api/Phalcon_Db_Profiler.rst b/id/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/id/api/Phalcon_Db_Profiler.rst +++ b/id/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/id/api/Phalcon_Db_RawValue.rst b/id/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/id/api/Phalcon_Db_RawValue.rst +++ b/id/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/id/api/Phalcon_Db_Reference.rst b/id/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/id/api/Phalcon_Db_Reference.rst +++ b/id/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/id/api/Phalcon_Db_Result_Pdo.rst b/id/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/id/api/Phalcon_Db_Result_Pdo.rst +++ b/id/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/id/api/Phalcon_Debug.rst b/id/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/id/api/Phalcon_Debug.rst +++ b/id/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/id/api/Phalcon_Debug_Dump.rst b/id/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/id/api/Phalcon_Debug_Dump.rst +++ b/id/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/id/api/Phalcon_Di.rst b/id/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/id/api/Phalcon_Di.rst +++ b/id/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/id/api/Phalcon_Di_FactoryDefault.rst b/id/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/id/api/Phalcon_Di_FactoryDefault.rst +++ b/id/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/id/api/Phalcon_Di_FactoryDefault_Cli.rst b/id/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/id/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/id/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/id/api/Phalcon_Di_Injectable.rst b/id/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/id/api/Phalcon_Di_Injectable.rst +++ b/id/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/id/api/Phalcon_Di_Service.rst b/id/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/id/api/Phalcon_Di_Service.rst +++ b/id/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/id/api/Phalcon_Dispatcher.rst b/id/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/id/api/Phalcon_Dispatcher.rst +++ b/id/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/id/api/Phalcon_Escaper.rst b/id/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/id/api/Phalcon_Escaper.rst +++ b/id/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/id/api/Phalcon_Events_Event.rst b/id/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/id/api/Phalcon_Events_Event.rst +++ b/id/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/id/api/Phalcon_Events_Manager.rst b/id/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/id/api/Phalcon_Events_Manager.rst +++ b/id/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/id/api/Phalcon_Filter.rst b/id/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/id/api/Phalcon_Filter.rst +++ b/id/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/id/api/Phalcon_Flash.rst b/id/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/id/api/Phalcon_Flash.rst +++ b/id/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/id/api/Phalcon_Flash_Direct.rst b/id/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/id/api/Phalcon_Flash_Direct.rst +++ b/id/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/id/api/Phalcon_Flash_Session.rst b/id/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/id/api/Phalcon_Flash_Session.rst +++ b/id/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/id/api/Phalcon_Forms_Element.rst b/id/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/id/api/Phalcon_Forms_Element.rst +++ b/id/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_Check.rst b/id/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/id/api/Phalcon_Forms_Element_Check.rst +++ b/id/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_Date.rst b/id/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/id/api/Phalcon_Forms_Element_Date.rst +++ b/id/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_Email.rst b/id/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/id/api/Phalcon_Forms_Element_Email.rst +++ b/id/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_File.rst b/id/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/id/api/Phalcon_Forms_Element_File.rst +++ b/id/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_Hidden.rst b/id/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/id/api/Phalcon_Forms_Element_Hidden.rst +++ b/id/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_Numeric.rst b/id/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/id/api/Phalcon_Forms_Element_Numeric.rst +++ b/id/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_Password.rst b/id/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/id/api/Phalcon_Forms_Element_Password.rst +++ b/id/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_Radio.rst b/id/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/id/api/Phalcon_Forms_Element_Radio.rst +++ b/id/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_Select.rst b/id/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/id/api/Phalcon_Forms_Element_Select.rst +++ b/id/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_Submit.rst b/id/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/id/api/Phalcon_Forms_Element_Submit.rst +++ b/id/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_Text.rst b/id/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/id/api/Phalcon_Forms_Element_Text.rst +++ b/id/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Element_TextArea.rst b/id/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/id/api/Phalcon_Forms_Element_TextArea.rst +++ b/id/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/id/api/Phalcon_Forms_Manager.rst b/id/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/id/api/Phalcon_Forms_Manager.rst +++ b/id/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/id/api/Phalcon_Http_Cookie.rst b/id/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/id/api/Phalcon_Http_Cookie.rst +++ b/id/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/id/api/Phalcon_Http_Request.rst b/id/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/id/api/Phalcon_Http_Request.rst +++ b/id/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/id/api/Phalcon_Http_Request_File.rst b/id/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/id/api/Phalcon_Http_Request_File.rst +++ b/id/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/id/api/Phalcon_Http_Response.rst b/id/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/id/api/Phalcon_Http_Response.rst +++ b/id/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/id/api/Phalcon_Http_Response_Cookies.rst b/id/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/id/api/Phalcon_Http_Response_Cookies.rst +++ b/id/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/id/api/Phalcon_Image_Adapter.rst b/id/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/id/api/Phalcon_Image_Adapter.rst +++ b/id/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/id/api/Phalcon_Image_Adapter_Gd.rst b/id/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/id/api/Phalcon_Image_Adapter_Gd.rst +++ b/id/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/id/api/Phalcon_Image_Adapter_Imagick.rst b/id/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/id/api/Phalcon_Image_Adapter_Imagick.rst +++ b/id/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/id/api/Phalcon_Loader.rst b/id/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/id/api/Phalcon_Loader.rst +++ b/id/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/id/api/Phalcon_Logger_Adapter.rst b/id/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/id/api/Phalcon_Logger_Adapter.rst +++ b/id/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/id/api/Phalcon_Logger_Adapter_File.rst b/id/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/id/api/Phalcon_Logger_Adapter_File.rst +++ b/id/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/id/api/Phalcon_Logger_Adapter_Firephp.rst b/id/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/id/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/id/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/id/api/Phalcon_Logger_Adapter_Stream.rst b/id/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/id/api/Phalcon_Logger_Adapter_Stream.rst +++ b/id/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/id/api/Phalcon_Logger_Adapter_Syslog.rst b/id/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/id/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/id/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/id/api/Phalcon_Mvc_Application.rst b/id/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/id/api/Phalcon_Mvc_Application.rst +++ b/id/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/id/api/Phalcon_Mvc_Collection.rst b/id/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/id/api/Phalcon_Mvc_Collection.rst +++ b/id/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/id/api/Phalcon_Mvc_Collection_Behavior.rst b/id/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/id/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/id/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/id/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/id/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/id/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/id/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/id/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/id/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/id/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/id/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/id/api/Phalcon_Mvc_Collection_Document.rst b/id/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/id/api/Phalcon_Mvc_Collection_Document.rst +++ b/id/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/id/api/Phalcon_Mvc_Collection_Manager.rst b/id/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/id/api/Phalcon_Mvc_Collection_Manager.rst +++ b/id/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/id/api/Phalcon_Mvc_Controller.rst b/id/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/id/api/Phalcon_Mvc_Controller.rst +++ b/id/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/id/api/Phalcon_Mvc_Dispatcher.rst b/id/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/id/api/Phalcon_Mvc_Dispatcher.rst +++ b/id/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/id/api/Phalcon_Mvc_Micro.rst b/id/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/id/api/Phalcon_Mvc_Micro.rst +++ b/id/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/id/api/Phalcon_Mvc_Model.rst b/id/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/id/api/Phalcon_Mvc_Model.rst +++ b/id/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/id/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/id/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/id/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/id/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/id/api/Phalcon_Mvc_Model_Criteria.rst b/id/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/id/api/Phalcon_Mvc_Model_Criteria.rst +++ b/id/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/id/api/Phalcon_Mvc_Model_Manager.rst b/id/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/id/api/Phalcon_Mvc_Model_Manager.rst +++ b/id/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/id/api/Phalcon_Mvc_Model_Message.rst b/id/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/id/api/Phalcon_Mvc_Model_Message.rst +++ b/id/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/id/api/Phalcon_Mvc_Model_MetaData.rst b/id/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/id/api/Phalcon_Mvc_Model_MetaData.rst +++ b/id/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/id/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/id/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/id/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/id/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/id/api/Phalcon_Mvc_Model_MetaData_Files.rst b/id/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/id/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/id/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/id/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/id/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/id/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/id/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/id/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/id/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/id/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/id/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/id/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/id/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/id/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/id/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/id/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/id/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/id/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/id/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/id/api/Phalcon_Mvc_Model_MetaData_Session.rst b/id/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/id/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/id/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/id/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/id/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/id/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/id/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/id/api/Phalcon_Mvc_Model_Query.rst b/id/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/id/api/Phalcon_Mvc_Model_Query.rst +++ b/id/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/id/api/Phalcon_Mvc_Model_Query_Builder.rst b/id/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/id/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/id/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/id/api/Phalcon_Mvc_Model_Query_Lang.rst b/id/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/id/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/id/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/id/api/Phalcon_Mvc_Model_Relation.rst b/id/api/Phalcon_Mvc_Model_Relation.rst index bbd49acbd3ac..7a0c5587b554 100644 --- a/id/api/Phalcon_Mvc_Model_Relation.rst +++ b/id/api/Phalcon_Mvc_Model_Relation.rst @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned diff --git a/id/api/Phalcon_Mvc_Model_Resultset.rst b/id/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/id/api/Phalcon_Mvc_Model_Resultset.rst +++ b/id/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/id/api/Phalcon_Mvc_Model_Transaction.rst b/id/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/id/api/Phalcon_Mvc_Model_Transaction.rst +++ b/id/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/id/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/id/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/id/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/id/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/id/api/Phalcon_Mvc_Model_ValidationFailed.rst b/id/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/id/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/id/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/id/api/Phalcon_Mvc_Model_Validator.rst b/id/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/id/api/Phalcon_Mvc_Model_Validator.rst +++ b/id/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/id/api/Phalcon_Mvc_Model_Validator_Email.rst b/id/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/id/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/id/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/id/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/id/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/id/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/id/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/id/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/id/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/id/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/id/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/id/api/Phalcon_Mvc_Model_Validator_Ip.rst b/id/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/id/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/id/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/id/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/id/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/id/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/id/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/id/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/id/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/id/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/id/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/id/api/Phalcon_Mvc_Model_Validator_Regex.rst b/id/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/id/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/id/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/id/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/id/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/id/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/id/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/id/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/id/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/id/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/id/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/id/api/Phalcon_Mvc_Model_Validator_Url.rst b/id/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/id/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/id/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/id/api/Phalcon_Mvc_Router.rst b/id/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/id/api/Phalcon_Mvc_Router.rst +++ b/id/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/id/api/Phalcon_Mvc_Router_Annotations.rst b/id/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/id/api/Phalcon_Mvc_Router_Annotations.rst +++ b/id/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/id/api/Phalcon_Mvc_Router_Group.rst b/id/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/id/api/Phalcon_Mvc_Router_Group.rst +++ b/id/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/id/api/Phalcon_Mvc_Router_Route.rst b/id/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/id/api/Phalcon_Mvc_Router_Route.rst +++ b/id/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/id/api/Phalcon_Mvc_Url.rst b/id/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/id/api/Phalcon_Mvc_Url.rst +++ b/id/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/id/api/Phalcon_Mvc_View.rst b/id/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/id/api/Phalcon_Mvc_View.rst +++ b/id/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/id/api/Phalcon_Mvc_View_Engine.rst b/id/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/id/api/Phalcon_Mvc_View_Engine.rst +++ b/id/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/id/api/Phalcon_Mvc_View_Engine_Php.rst b/id/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/id/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/id/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/id/api/Phalcon_Mvc_View_Engine_Volt.rst b/id/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/id/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/id/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/id/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/id/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/id/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/id/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/id/api/Phalcon_Mvc_View_Simple.rst b/id/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/id/api/Phalcon_Mvc_View_Simple.rst +++ b/id/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/id/api/Phalcon_Paginator_Adapter.rst b/id/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/id/api/Phalcon_Paginator_Adapter.rst +++ b/id/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/id/api/Phalcon_Paginator_Adapter_Model.rst b/id/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/id/api/Phalcon_Paginator_Adapter_Model.rst +++ b/id/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/id/api/Phalcon_Paginator_Adapter_NativeArray.rst b/id/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/id/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/id/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/id/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/id/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/id/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/id/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/id/api/Phalcon_Queue_Beanstalk.rst b/id/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/id/api/Phalcon_Queue_Beanstalk.rst +++ b/id/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/id/api/Phalcon_Queue_Beanstalk_Job.rst b/id/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/id/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/id/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/id/api/Phalcon_Registry.rst b/id/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/id/api/Phalcon_Registry.rst +++ b/id/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/id/api/Phalcon_Security.rst b/id/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/id/api/Phalcon_Security.rst +++ b/id/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/id/api/Phalcon_Security_Random.rst b/id/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/id/api/Phalcon_Security_Random.rst +++ b/id/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/id/api/Phalcon_Session_Adapter.rst b/id/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/id/api/Phalcon_Session_Adapter.rst +++ b/id/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/id/api/Phalcon_Session_Adapter_Files.rst b/id/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/id/api/Phalcon_Session_Adapter_Files.rst +++ b/id/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/id/api/Phalcon_Session_Adapter_Libmemcached.rst b/id/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/id/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/id/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/id/api/Phalcon_Session_Adapter_Memcache.rst b/id/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/id/api/Phalcon_Session_Adapter_Memcache.rst +++ b/id/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/id/api/Phalcon_Session_Adapter_Redis.rst b/id/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/id/api/Phalcon_Session_Adapter_Redis.rst +++ b/id/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/id/api/Phalcon_Session_Bag.rst b/id/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/id/api/Phalcon_Session_Bag.rst +++ b/id/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/id/api/Phalcon_Tag.rst b/id/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/id/api/Phalcon_Tag.rst +++ b/id/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/id/api/Phalcon_Translate_Adapter_Gettext.rst b/id/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/id/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/id/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/id/api/Phalcon_Validation.rst b/id/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/id/api/Phalcon_Validation.rst +++ b/id/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/id/api/Phalcon_Validation_CombinedFieldsValidator.rst b/id/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/id/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/id/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Message.rst b/id/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/id/api/Phalcon_Validation_Message.rst +++ b/id/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/id/api/Phalcon_Validation_Message_Group.rst b/id/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/id/api/Phalcon_Validation_Message_Group.rst +++ b/id/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/id/api/Phalcon_Validation_Validator.rst b/id/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/id/api/Phalcon_Validation_Validator.rst +++ b/id/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Alnum.rst b/id/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/id/api/Phalcon_Validation_Validator_Alnum.rst +++ b/id/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Alpha.rst b/id/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/id/api/Phalcon_Validation_Validator_Alpha.rst +++ b/id/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Between.rst b/id/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/id/api/Phalcon_Validation_Validator_Between.rst +++ b/id/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Confirmation.rst b/id/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/id/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/id/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_CreditCard.rst b/id/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/id/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/id/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Date.rst b/id/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/id/api/Phalcon_Validation_Validator_Date.rst +++ b/id/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Digit.rst b/id/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/id/api/Phalcon_Validation_Validator_Digit.rst +++ b/id/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Email.rst b/id/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/id/api/Phalcon_Validation_Validator_Email.rst +++ b/id/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_ExclusionIn.rst b/id/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/id/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/id/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_File.rst b/id/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/id/api/Phalcon_Validation_Validator_File.rst +++ b/id/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Identical.rst b/id/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/id/api/Phalcon_Validation_Validator_Identical.rst +++ b/id/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_InclusionIn.rst b/id/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/id/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/id/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Numericality.rst b/id/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/id/api/Phalcon_Validation_Validator_Numericality.rst +++ b/id/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_PresenceOf.rst b/id/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/id/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/id/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Regex.rst b/id/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/id/api/Phalcon_Validation_Validator_Regex.rst +++ b/id/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_StringLength.rst b/id/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/id/api/Phalcon_Validation_Validator_StringLength.rst +++ b/id/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Uniqueness.rst b/id/api/Phalcon_Validation_Validator_Uniqueness.rst index af0bde58d45d..8af5174ddfba 100644 --- a/id/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/id/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,59 +10,84 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; - Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); - In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); + $validator->add( + "username", + new UniquenessValidator() + ); - Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); - It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); @@ -106,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Validation_Validator_Url.rst b/id/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/id/api/Phalcon_Validation_Validator_Url.rst +++ b/id/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/id/api/Phalcon_Version.rst b/id/api/Phalcon_Version.rst index 4322c6cb17bb..77d94d7b0e5a 100644 --- a/id/api/Phalcon_Version.rst +++ b/id/api/Phalcon_Version.rst @@ -27,51 +27,61 @@ 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. +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. final protected static **_getSpecial** (*mixed* $special) -Translates a number to a special release If Special release = 1 this function will return ALPHA +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -Returns the active version (string) +Returns the active version (string) .. code-block:: php Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/ja/api/Phalcon_Annotations_Adapter_Apc.rst b/ja/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/ja/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/ja/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/ja/api/Phalcon_Annotations_Adapter_Files.rst b/ja/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/ja/api/Phalcon_Annotations_Adapter_Files.rst +++ b/ja/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/ja/api/Phalcon_Annotations_Adapter_Memory.rst b/ja/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/ja/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/ja/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/ja/api/Phalcon_Annotations_Adapter_Xcache.rst b/ja/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/ja/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/ja/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/ja/api/Phalcon_Annotations_Reflection.rst b/ja/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/ja/api/Phalcon_Annotations_Reflection.rst +++ b/ja/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/ja/api/Phalcon_Application.rst b/ja/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/ja/api/Phalcon_Application.rst +++ b/ja/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/ja/api/Phalcon_Assets_Filters_Cssmin.rst b/ja/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/ja/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/ja/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/ja/api/Phalcon_Assets_Filters_Jsmin.rst b/ja/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/ja/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/ja/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/ja/api/Phalcon_Assets_Inline.rst b/ja/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/ja/api/Phalcon_Assets_Inline.rst +++ b/ja/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/ja/api/Phalcon_Assets_Resource.rst b/ja/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/ja/api/Phalcon_Assets_Resource.rst +++ b/ja/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/ja/api/Phalcon_Assets_Resource_Js.rst b/ja/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/ja/api/Phalcon_Assets_Resource_Js.rst +++ b/ja/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/ja/api/Phalcon_Cache_Backend.rst b/ja/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/ja/api/Phalcon_Cache_Backend.rst +++ b/ja/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/ja/api/Phalcon_Cache_Backend_Apc.rst b/ja/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/ja/api/Phalcon_Cache_Backend_Apc.rst +++ b/ja/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/ja/api/Phalcon_Cache_Backend_File.rst b/ja/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/ja/api/Phalcon_Cache_Backend_File.rst +++ b/ja/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/ja/api/Phalcon_Cache_Backend_Libmemcached.rst b/ja/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/ja/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/ja/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/ja/api/Phalcon_Cache_Backend_Memcache.rst b/ja/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/ja/api/Phalcon_Cache_Backend_Memcache.rst +++ b/ja/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/ja/api/Phalcon_Cache_Backend_Memory.rst b/ja/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/ja/api/Phalcon_Cache_Backend_Memory.rst +++ b/ja/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/ja/api/Phalcon_Cache_Backend_Mongo.rst b/ja/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/ja/api/Phalcon_Cache_Backend_Mongo.rst +++ b/ja/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/ja/api/Phalcon_Cache_Backend_Redis.rst b/ja/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/ja/api/Phalcon_Cache_Backend_Redis.rst +++ b/ja/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/ja/api/Phalcon_Cache_Backend_Xcache.rst b/ja/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/ja/api/Phalcon_Cache_Backend_Xcache.rst +++ b/ja/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/ja/api/Phalcon_Cache_Frontend_Base64.rst b/ja/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/ja/api/Phalcon_Cache_Frontend_Base64.rst +++ b/ja/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/ja/api/Phalcon_Cache_Frontend_Data.rst b/ja/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/ja/api/Phalcon_Cache_Frontend_Data.rst +++ b/ja/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/ja/api/Phalcon_Cache_Frontend_Igbinary.rst b/ja/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/ja/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/ja/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/ja/api/Phalcon_Cache_Frontend_Json.rst b/ja/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/ja/api/Phalcon_Cache_Frontend_Json.rst +++ b/ja/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/ja/api/Phalcon_Cache_Frontend_Msgpack.rst b/ja/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/ja/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/ja/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/ja/api/Phalcon_Cache_Frontend_None.rst b/ja/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/ja/api/Phalcon_Cache_Frontend_None.rst +++ b/ja/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/ja/api/Phalcon_Cache_Frontend_Output.rst b/ja/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/ja/api/Phalcon_Cache_Frontend_Output.rst +++ b/ja/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/ja/api/Phalcon_Cache_Multiple.rst b/ja/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/ja/api/Phalcon_Cache_Multiple.rst +++ b/ja/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/ja/api/Phalcon_Cli_Console.rst b/ja/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/ja/api/Phalcon_Cli_Console.rst +++ b/ja/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/ja/api/Phalcon_Cli_Dispatcher.rst b/ja/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/ja/api/Phalcon_Cli_Dispatcher.rst +++ b/ja/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/ja/api/Phalcon_Cli_Router.rst b/ja/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/ja/api/Phalcon_Cli_Router.rst +++ b/ja/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/ja/api/Phalcon_Cli_Router_Route.rst b/ja/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/ja/api/Phalcon_Cli_Router_Route.rst +++ b/ja/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/ja/api/Phalcon_Cli_Task.rst b/ja/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/ja/api/Phalcon_Cli_Task.rst +++ b/ja/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/ja/api/Phalcon_Config.rst b/ja/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/ja/api/Phalcon_Config.rst +++ b/ja/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/ja/api/Phalcon_Config_Adapter_Ini.rst b/ja/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/ja/api/Phalcon_Config_Adapter_Ini.rst +++ b/ja/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/ja/api/Phalcon_Config_Adapter_Json.rst b/ja/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/ja/api/Phalcon_Config_Adapter_Json.rst +++ b/ja/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/ja/api/Phalcon_Config_Adapter_Php.rst b/ja/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/ja/api/Phalcon_Config_Adapter_Php.rst +++ b/ja/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/ja/api/Phalcon_Config_Adapter_Yaml.rst b/ja/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/ja/api/Phalcon_Config_Adapter_Yaml.rst +++ b/ja/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/ja/api/Phalcon_Crypt.rst b/ja/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/ja/api/Phalcon_Crypt.rst +++ b/ja/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/ja/api/Phalcon_Db.rst b/ja/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/ja/api/Phalcon_Db.rst +++ b/ja/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/ja/api/Phalcon_Db_Adapter.rst b/ja/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/ja/api/Phalcon_Db_Adapter.rst +++ b/ja/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/ja/api/Phalcon_Db_Adapter_Pdo.rst b/ja/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/ja/api/Phalcon_Db_Adapter_Pdo.rst +++ b/ja/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/ja/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/ja/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/ja/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/ja/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/ja/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/ja/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/ja/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/ja/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/ja/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/ja/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/ja/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/ja/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/ja/api/Phalcon_Db_Column.rst b/ja/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/ja/api/Phalcon_Db_Column.rst +++ b/ja/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/ja/api/Phalcon_Db_Dialect.rst b/ja/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/ja/api/Phalcon_Db_Dialect.rst +++ b/ja/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/ja/api/Phalcon_Db_Dialect_Mysql.rst b/ja/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/ja/api/Phalcon_Db_Dialect_Mysql.rst +++ b/ja/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/ja/api/Phalcon_Db_Dialect_Postgresql.rst b/ja/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/ja/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/ja/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/ja/api/Phalcon_Db_Dialect_Sqlite.rst b/ja/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/ja/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/ja/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/ja/api/Phalcon_Db_Index.rst b/ja/api/Phalcon_Db_Index.rst index 227b766ccbe8..415a456a64bd 100644 --- a/ja/api/Phalcon_Db_Index.rst +++ b/ja/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods diff --git a/ja/api/Phalcon_Db_Profiler.rst b/ja/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/ja/api/Phalcon_Db_Profiler.rst +++ b/ja/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/ja/api/Phalcon_Db_RawValue.rst b/ja/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/ja/api/Phalcon_Db_RawValue.rst +++ b/ja/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/ja/api/Phalcon_Db_Reference.rst b/ja/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/ja/api/Phalcon_Db_Reference.rst +++ b/ja/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/ja/api/Phalcon_Db_Result_Pdo.rst b/ja/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/ja/api/Phalcon_Db_Result_Pdo.rst +++ b/ja/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/ja/api/Phalcon_Debug.rst b/ja/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/ja/api/Phalcon_Debug.rst +++ b/ja/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/ja/api/Phalcon_Debug_Dump.rst b/ja/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/ja/api/Phalcon_Debug_Dump.rst +++ b/ja/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/ja/api/Phalcon_Di.rst b/ja/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/ja/api/Phalcon_Di.rst +++ b/ja/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/ja/api/Phalcon_Di_FactoryDefault.rst b/ja/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/ja/api/Phalcon_Di_FactoryDefault.rst +++ b/ja/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/ja/api/Phalcon_Di_FactoryDefault_Cli.rst b/ja/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/ja/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/ja/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/ja/api/Phalcon_Di_Injectable.rst b/ja/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/ja/api/Phalcon_Di_Injectable.rst +++ b/ja/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/ja/api/Phalcon_Di_Service.rst b/ja/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/ja/api/Phalcon_Di_Service.rst +++ b/ja/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/ja/api/Phalcon_Dispatcher.rst b/ja/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/ja/api/Phalcon_Dispatcher.rst +++ b/ja/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/ja/api/Phalcon_Escaper.rst b/ja/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/ja/api/Phalcon_Escaper.rst +++ b/ja/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/ja/api/Phalcon_Events_Event.rst b/ja/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/ja/api/Phalcon_Events_Event.rst +++ b/ja/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/ja/api/Phalcon_Events_Manager.rst b/ja/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/ja/api/Phalcon_Events_Manager.rst +++ b/ja/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/ja/api/Phalcon_Filter.rst b/ja/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/ja/api/Phalcon_Filter.rst +++ b/ja/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/ja/api/Phalcon_Flash.rst b/ja/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/ja/api/Phalcon_Flash.rst +++ b/ja/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/ja/api/Phalcon_Flash_Direct.rst b/ja/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/ja/api/Phalcon_Flash_Direct.rst +++ b/ja/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/ja/api/Phalcon_Flash_Session.rst b/ja/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/ja/api/Phalcon_Flash_Session.rst +++ b/ja/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/ja/api/Phalcon_Forms_Element.rst b/ja/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/ja/api/Phalcon_Forms_Element.rst +++ b/ja/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_Check.rst b/ja/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/ja/api/Phalcon_Forms_Element_Check.rst +++ b/ja/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_Date.rst b/ja/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/ja/api/Phalcon_Forms_Element_Date.rst +++ b/ja/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_Email.rst b/ja/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/ja/api/Phalcon_Forms_Element_Email.rst +++ b/ja/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_File.rst b/ja/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/ja/api/Phalcon_Forms_Element_File.rst +++ b/ja/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_Hidden.rst b/ja/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/ja/api/Phalcon_Forms_Element_Hidden.rst +++ b/ja/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_Numeric.rst b/ja/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/ja/api/Phalcon_Forms_Element_Numeric.rst +++ b/ja/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_Password.rst b/ja/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/ja/api/Phalcon_Forms_Element_Password.rst +++ b/ja/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_Radio.rst b/ja/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/ja/api/Phalcon_Forms_Element_Radio.rst +++ b/ja/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_Select.rst b/ja/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/ja/api/Phalcon_Forms_Element_Select.rst +++ b/ja/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_Submit.rst b/ja/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/ja/api/Phalcon_Forms_Element_Submit.rst +++ b/ja/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_Text.rst b/ja/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/ja/api/Phalcon_Forms_Element_Text.rst +++ b/ja/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Element_TextArea.rst b/ja/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/ja/api/Phalcon_Forms_Element_TextArea.rst +++ b/ja/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ja/api/Phalcon_Forms_Manager.rst b/ja/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/ja/api/Phalcon_Forms_Manager.rst +++ b/ja/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/ja/api/Phalcon_Http_Cookie.rst b/ja/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/ja/api/Phalcon_Http_Cookie.rst +++ b/ja/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/ja/api/Phalcon_Http_Request.rst b/ja/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/ja/api/Phalcon_Http_Request.rst +++ b/ja/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/ja/api/Phalcon_Http_Request_File.rst b/ja/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/ja/api/Phalcon_Http_Request_File.rst +++ b/ja/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/ja/api/Phalcon_Http_Response.rst b/ja/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/ja/api/Phalcon_Http_Response.rst +++ b/ja/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/ja/api/Phalcon_Http_Response_Cookies.rst b/ja/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/ja/api/Phalcon_Http_Response_Cookies.rst +++ b/ja/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/ja/api/Phalcon_Image_Adapter.rst b/ja/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/ja/api/Phalcon_Image_Adapter.rst +++ b/ja/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/ja/api/Phalcon_Image_Adapter_Gd.rst b/ja/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/ja/api/Phalcon_Image_Adapter_Gd.rst +++ b/ja/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/ja/api/Phalcon_Image_Adapter_Imagick.rst b/ja/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/ja/api/Phalcon_Image_Adapter_Imagick.rst +++ b/ja/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/ja/api/Phalcon_Loader.rst b/ja/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/ja/api/Phalcon_Loader.rst +++ b/ja/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/ja/api/Phalcon_Logger_Adapter.rst b/ja/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/ja/api/Phalcon_Logger_Adapter.rst +++ b/ja/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/ja/api/Phalcon_Logger_Adapter_File.rst b/ja/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/ja/api/Phalcon_Logger_Adapter_File.rst +++ b/ja/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/ja/api/Phalcon_Logger_Adapter_Firephp.rst b/ja/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/ja/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/ja/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/ja/api/Phalcon_Logger_Adapter_Stream.rst b/ja/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/ja/api/Phalcon_Logger_Adapter_Stream.rst +++ b/ja/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/ja/api/Phalcon_Logger_Adapter_Syslog.rst b/ja/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/ja/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/ja/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/ja/api/Phalcon_Mvc_Application.rst b/ja/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/ja/api/Phalcon_Mvc_Application.rst +++ b/ja/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/ja/api/Phalcon_Mvc_Collection.rst b/ja/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/ja/api/Phalcon_Mvc_Collection.rst +++ b/ja/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/ja/api/Phalcon_Mvc_Collection_Behavior.rst b/ja/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/ja/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/ja/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/ja/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/ja/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/ja/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/ja/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/ja/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/ja/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/ja/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/ja/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/ja/api/Phalcon_Mvc_Collection_Document.rst b/ja/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/ja/api/Phalcon_Mvc_Collection_Document.rst +++ b/ja/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/ja/api/Phalcon_Mvc_Collection_Manager.rst b/ja/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/ja/api/Phalcon_Mvc_Collection_Manager.rst +++ b/ja/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/ja/api/Phalcon_Mvc_Controller.rst b/ja/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/ja/api/Phalcon_Mvc_Controller.rst +++ b/ja/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/ja/api/Phalcon_Mvc_Dispatcher.rst b/ja/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/ja/api/Phalcon_Mvc_Dispatcher.rst +++ b/ja/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/ja/api/Phalcon_Mvc_Micro.rst b/ja/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/ja/api/Phalcon_Mvc_Micro.rst +++ b/ja/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/ja/api/Phalcon_Mvc_Model.rst b/ja/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/ja/api/Phalcon_Mvc_Model.rst +++ b/ja/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/ja/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/ja/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/ja/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/ja/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/ja/api/Phalcon_Mvc_Model_Criteria.rst b/ja/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/ja/api/Phalcon_Mvc_Model_Criteria.rst +++ b/ja/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/ja/api/Phalcon_Mvc_Model_Manager.rst b/ja/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/ja/api/Phalcon_Mvc_Model_Manager.rst +++ b/ja/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/ja/api/Phalcon_Mvc_Model_Message.rst b/ja/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/ja/api/Phalcon_Mvc_Model_Message.rst +++ b/ja/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/ja/api/Phalcon_Mvc_Model_MetaData.rst b/ja/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/ja/api/Phalcon_Mvc_Model_MetaData.rst +++ b/ja/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ja/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/ja/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/ja/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/ja/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ja/api/Phalcon_Mvc_Model_MetaData_Files.rst b/ja/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/ja/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/ja/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ja/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/ja/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/ja/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/ja/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/ja/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/ja/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/ja/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/ja/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/ja/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/ja/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/ja/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/ja/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ja/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/ja/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/ja/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/ja/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/ja/api/Phalcon_Mvc_Model_MetaData_Session.rst b/ja/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/ja/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/ja/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ja/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/ja/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/ja/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/ja/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ja/api/Phalcon_Mvc_Model_Query.rst b/ja/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/ja/api/Phalcon_Mvc_Model_Query.rst +++ b/ja/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/ja/api/Phalcon_Mvc_Model_Query_Builder.rst b/ja/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/ja/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/ja/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/ja/api/Phalcon_Mvc_Model_Query_Lang.rst b/ja/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/ja/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/ja/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/ja/api/Phalcon_Mvc_Model_Relation.rst b/ja/api/Phalcon_Mvc_Model_Relation.rst index bbd49acbd3ac..7a0c5587b554 100644 --- a/ja/api/Phalcon_Mvc_Model_Relation.rst +++ b/ja/api/Phalcon_Mvc_Model_Relation.rst @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned diff --git a/ja/api/Phalcon_Mvc_Model_Resultset.rst b/ja/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/ja/api/Phalcon_Mvc_Model_Resultset.rst +++ b/ja/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/ja/api/Phalcon_Mvc_Model_Transaction.rst b/ja/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/ja/api/Phalcon_Mvc_Model_Transaction.rst +++ b/ja/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/ja/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/ja/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/ja/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/ja/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/ja/api/Phalcon_Mvc_Model_ValidationFailed.rst b/ja/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/ja/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/ja/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/ja/api/Phalcon_Mvc_Model_Validator.rst b/ja/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/ja/api/Phalcon_Mvc_Model_Validator_Email.rst b/ja/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ja/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/ja/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ja/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/ja/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ja/api/Phalcon_Mvc_Model_Validator_Ip.rst b/ja/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ja/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/ja/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ja/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/ja/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ja/api/Phalcon_Mvc_Model_Validator_Regex.rst b/ja/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/ja/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/ja/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ja/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/ja/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ja/api/Phalcon_Mvc_Model_Validator_Url.rst b/ja/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/ja/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/ja/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ja/api/Phalcon_Mvc_Router.rst b/ja/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/ja/api/Phalcon_Mvc_Router.rst +++ b/ja/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/ja/api/Phalcon_Mvc_Router_Annotations.rst b/ja/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/ja/api/Phalcon_Mvc_Router_Annotations.rst +++ b/ja/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/ja/api/Phalcon_Mvc_Router_Group.rst b/ja/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/ja/api/Phalcon_Mvc_Router_Group.rst +++ b/ja/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/ja/api/Phalcon_Mvc_Router_Route.rst b/ja/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/ja/api/Phalcon_Mvc_Router_Route.rst +++ b/ja/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/ja/api/Phalcon_Mvc_Url.rst b/ja/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/ja/api/Phalcon_Mvc_Url.rst +++ b/ja/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/ja/api/Phalcon_Mvc_View.rst b/ja/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/ja/api/Phalcon_Mvc_View.rst +++ b/ja/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/ja/api/Phalcon_Mvc_View_Engine.rst b/ja/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/ja/api/Phalcon_Mvc_View_Engine.rst +++ b/ja/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/ja/api/Phalcon_Mvc_View_Engine_Php.rst b/ja/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/ja/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/ja/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/ja/api/Phalcon_Mvc_View_Engine_Volt.rst b/ja/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/ja/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/ja/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/ja/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/ja/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/ja/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/ja/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/ja/api/Phalcon_Mvc_View_Simple.rst b/ja/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/ja/api/Phalcon_Mvc_View_Simple.rst +++ b/ja/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/ja/api/Phalcon_Paginator_Adapter.rst b/ja/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/ja/api/Phalcon_Paginator_Adapter.rst +++ b/ja/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/ja/api/Phalcon_Paginator_Adapter_Model.rst b/ja/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/ja/api/Phalcon_Paginator_Adapter_Model.rst +++ b/ja/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/ja/api/Phalcon_Paginator_Adapter_NativeArray.rst b/ja/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/ja/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/ja/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/ja/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/ja/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/ja/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/ja/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/ja/api/Phalcon_Queue_Beanstalk.rst b/ja/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/ja/api/Phalcon_Queue_Beanstalk.rst +++ b/ja/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/ja/api/Phalcon_Queue_Beanstalk_Job.rst b/ja/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/ja/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/ja/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/ja/api/Phalcon_Registry.rst b/ja/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/ja/api/Phalcon_Registry.rst +++ b/ja/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/ja/api/Phalcon_Security.rst b/ja/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/ja/api/Phalcon_Security.rst +++ b/ja/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/ja/api/Phalcon_Security_Random.rst b/ja/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/ja/api/Phalcon_Security_Random.rst +++ b/ja/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/ja/api/Phalcon_Session_Adapter.rst b/ja/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/ja/api/Phalcon_Session_Adapter.rst +++ b/ja/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/ja/api/Phalcon_Session_Adapter_Files.rst b/ja/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/ja/api/Phalcon_Session_Adapter_Files.rst +++ b/ja/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/ja/api/Phalcon_Session_Adapter_Libmemcached.rst b/ja/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/ja/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/ja/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/ja/api/Phalcon_Session_Adapter_Memcache.rst b/ja/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/ja/api/Phalcon_Session_Adapter_Memcache.rst +++ b/ja/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/ja/api/Phalcon_Session_Adapter_Redis.rst b/ja/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/ja/api/Phalcon_Session_Adapter_Redis.rst +++ b/ja/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/ja/api/Phalcon_Session_Bag.rst b/ja/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/ja/api/Phalcon_Session_Bag.rst +++ b/ja/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/ja/api/Phalcon_Tag.rst b/ja/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/ja/api/Phalcon_Tag.rst +++ b/ja/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/ja/api/Phalcon_Translate_Adapter_Gettext.rst b/ja/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/ja/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/ja/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/ja/api/Phalcon_Validation.rst b/ja/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/ja/api/Phalcon_Validation.rst +++ b/ja/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/ja/api/Phalcon_Validation_CombinedFieldsValidator.rst b/ja/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/ja/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/ja/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Message.rst b/ja/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/ja/api/Phalcon_Validation_Message.rst +++ b/ja/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/ja/api/Phalcon_Validation_Message_Group.rst b/ja/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/ja/api/Phalcon_Validation_Message_Group.rst +++ b/ja/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/ja/api/Phalcon_Validation_Validator.rst b/ja/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/ja/api/Phalcon_Validation_Validator.rst +++ b/ja/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Alnum.rst b/ja/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/ja/api/Phalcon_Validation_Validator_Alnum.rst +++ b/ja/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Alpha.rst b/ja/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/ja/api/Phalcon_Validation_Validator_Alpha.rst +++ b/ja/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Between.rst b/ja/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/ja/api/Phalcon_Validation_Validator_Between.rst +++ b/ja/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Confirmation.rst b/ja/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/ja/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/ja/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_CreditCard.rst b/ja/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/ja/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/ja/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Date.rst b/ja/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/ja/api/Phalcon_Validation_Validator_Date.rst +++ b/ja/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Digit.rst b/ja/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/ja/api/Phalcon_Validation_Validator_Digit.rst +++ b/ja/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Email.rst b/ja/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/ja/api/Phalcon_Validation_Validator_Email.rst +++ b/ja/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_ExclusionIn.rst b/ja/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/ja/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/ja/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_File.rst b/ja/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/ja/api/Phalcon_Validation_Validator_File.rst +++ b/ja/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Identical.rst b/ja/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/ja/api/Phalcon_Validation_Validator_Identical.rst +++ b/ja/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_InclusionIn.rst b/ja/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/ja/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/ja/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Numericality.rst b/ja/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/ja/api/Phalcon_Validation_Validator_Numericality.rst +++ b/ja/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_PresenceOf.rst b/ja/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/ja/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/ja/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Regex.rst b/ja/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/ja/api/Phalcon_Validation_Validator_Regex.rst +++ b/ja/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_StringLength.rst b/ja/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/ja/api/Phalcon_Validation_Validator_StringLength.rst +++ b/ja/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Uniqueness.rst b/ja/api/Phalcon_Validation_Validator_Uniqueness.rst index af0bde58d45d..8af5174ddfba 100644 --- a/ja/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/ja/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,59 +10,84 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; - Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); - In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); + $validator->add( + "username", + new UniquenessValidator() + ); - Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); - It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); @@ -106,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Validation_Validator_Url.rst b/ja/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/ja/api/Phalcon_Validation_Validator_Url.rst +++ b/ja/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ja/api/Phalcon_Version.rst b/ja/api/Phalcon_Version.rst index 33cc05f5bd02..77d94d7b0e5a 100644 --- a/ja/api/Phalcon_Version.rst +++ b/ja/api/Phalcon_Version.rst @@ -6,10 +6,10 @@ Class **Phalcon\\Version** :raw-html:`Source on GitHub` -このクラスはインストールされたフレームワークのバージョンを参照できます。 +This class allows to get the installed version of the framework -定数 +Constants --------- *integer* **VERSION_MAJOR** @@ -22,53 +22,67 @@ Class **Phalcon\\Version** *integer* **VERSION_SPECIAL_NUMBER** -メソッド +Methods ------- protected static **_getVersion** () -バージョン番号を示す。フォーマットは ABBCCDE となる。それぞれ、A はメジャーバージョン、B は 2 桁で中間バージョン、C は 2 桁でマイナーバージョン、D は特別リリース属性を示し、1 は Alpha、2 は Beta、3 は RC、4 は安定板を示す。E は特別リリースのバージョンの番号、例えば RC1 や Beta2 等を示す。 +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. final protected static **_getSpecial** (*mixed* $special) -特別リリースの番号を変換する。特別リリースの番号が 1 の場合、この関数は ALPHA を返す。 +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -アクティブなバージョンを文字列で返す。 +Returns the active version (string) .. code-block:: php Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/pl/api/Phalcon_Annotations_Adapter_Apc.rst b/pl/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/pl/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/pl/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/pl/api/Phalcon_Annotations_Adapter_Files.rst b/pl/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/pl/api/Phalcon_Annotations_Adapter_Files.rst +++ b/pl/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/pl/api/Phalcon_Annotations_Adapter_Memory.rst b/pl/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/pl/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/pl/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/pl/api/Phalcon_Annotations_Adapter_Xcache.rst b/pl/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/pl/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/pl/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/pl/api/Phalcon_Annotations_Reflection.rst b/pl/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/pl/api/Phalcon_Annotations_Reflection.rst +++ b/pl/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/pl/api/Phalcon_Application.rst b/pl/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/pl/api/Phalcon_Application.rst +++ b/pl/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/pl/api/Phalcon_Assets_Filters_Cssmin.rst b/pl/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/pl/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/pl/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/pl/api/Phalcon_Assets_Filters_Jsmin.rst b/pl/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/pl/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/pl/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/pl/api/Phalcon_Assets_Inline.rst b/pl/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/pl/api/Phalcon_Assets_Inline.rst +++ b/pl/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/pl/api/Phalcon_Assets_Resource.rst b/pl/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/pl/api/Phalcon_Assets_Resource.rst +++ b/pl/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/pl/api/Phalcon_Assets_Resource_Js.rst b/pl/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/pl/api/Phalcon_Assets_Resource_Js.rst +++ b/pl/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/pl/api/Phalcon_Cache_Backend.rst b/pl/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/pl/api/Phalcon_Cache_Backend.rst +++ b/pl/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/pl/api/Phalcon_Cache_Backend_Apc.rst b/pl/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/pl/api/Phalcon_Cache_Backend_Apc.rst +++ b/pl/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/pl/api/Phalcon_Cache_Backend_File.rst b/pl/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/pl/api/Phalcon_Cache_Backend_File.rst +++ b/pl/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/pl/api/Phalcon_Cache_Backend_Libmemcached.rst b/pl/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/pl/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/pl/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/pl/api/Phalcon_Cache_Backend_Memcache.rst b/pl/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/pl/api/Phalcon_Cache_Backend_Memcache.rst +++ b/pl/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/pl/api/Phalcon_Cache_Backend_Memory.rst b/pl/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/pl/api/Phalcon_Cache_Backend_Memory.rst +++ b/pl/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/pl/api/Phalcon_Cache_Backend_Mongo.rst b/pl/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/pl/api/Phalcon_Cache_Backend_Mongo.rst +++ b/pl/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/pl/api/Phalcon_Cache_Backend_Redis.rst b/pl/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/pl/api/Phalcon_Cache_Backend_Redis.rst +++ b/pl/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/pl/api/Phalcon_Cache_Backend_Xcache.rst b/pl/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/pl/api/Phalcon_Cache_Backend_Xcache.rst +++ b/pl/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/pl/api/Phalcon_Cache_Frontend_Base64.rst b/pl/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/pl/api/Phalcon_Cache_Frontend_Base64.rst +++ b/pl/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/pl/api/Phalcon_Cache_Frontend_Data.rst b/pl/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/pl/api/Phalcon_Cache_Frontend_Data.rst +++ b/pl/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/pl/api/Phalcon_Cache_Frontend_Igbinary.rst b/pl/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/pl/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/pl/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/pl/api/Phalcon_Cache_Frontend_Json.rst b/pl/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/pl/api/Phalcon_Cache_Frontend_Json.rst +++ b/pl/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/pl/api/Phalcon_Cache_Frontend_Msgpack.rst b/pl/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/pl/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/pl/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/pl/api/Phalcon_Cache_Frontend_None.rst b/pl/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/pl/api/Phalcon_Cache_Frontend_None.rst +++ b/pl/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/pl/api/Phalcon_Cache_Frontend_Output.rst b/pl/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/pl/api/Phalcon_Cache_Frontend_Output.rst +++ b/pl/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/pl/api/Phalcon_Cache_Multiple.rst b/pl/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/pl/api/Phalcon_Cache_Multiple.rst +++ b/pl/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/pl/api/Phalcon_Cli_Console.rst b/pl/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/pl/api/Phalcon_Cli_Console.rst +++ b/pl/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/pl/api/Phalcon_Cli_Dispatcher.rst b/pl/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/pl/api/Phalcon_Cli_Dispatcher.rst +++ b/pl/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/pl/api/Phalcon_Cli_Router.rst b/pl/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/pl/api/Phalcon_Cli_Router.rst +++ b/pl/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/pl/api/Phalcon_Cli_Router_Route.rst b/pl/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/pl/api/Phalcon_Cli_Router_Route.rst +++ b/pl/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/pl/api/Phalcon_Cli_Task.rst b/pl/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/pl/api/Phalcon_Cli_Task.rst +++ b/pl/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/pl/api/Phalcon_Config.rst b/pl/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/pl/api/Phalcon_Config.rst +++ b/pl/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/pl/api/Phalcon_Config_Adapter_Ini.rst b/pl/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/pl/api/Phalcon_Config_Adapter_Ini.rst +++ b/pl/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/pl/api/Phalcon_Config_Adapter_Json.rst b/pl/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/pl/api/Phalcon_Config_Adapter_Json.rst +++ b/pl/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/pl/api/Phalcon_Config_Adapter_Php.rst b/pl/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/pl/api/Phalcon_Config_Adapter_Php.rst +++ b/pl/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/pl/api/Phalcon_Config_Adapter_Yaml.rst b/pl/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/pl/api/Phalcon_Config_Adapter_Yaml.rst +++ b/pl/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/pl/api/Phalcon_Crypt.rst b/pl/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/pl/api/Phalcon_Crypt.rst +++ b/pl/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/pl/api/Phalcon_Db.rst b/pl/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/pl/api/Phalcon_Db.rst +++ b/pl/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/pl/api/Phalcon_Db_Adapter.rst b/pl/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/pl/api/Phalcon_Db_Adapter.rst +++ b/pl/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/pl/api/Phalcon_Db_Adapter_Pdo.rst b/pl/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/pl/api/Phalcon_Db_Adapter_Pdo.rst +++ b/pl/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/pl/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/pl/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/pl/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/pl/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/pl/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/pl/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/pl/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/pl/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/pl/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/pl/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/pl/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/pl/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/pl/api/Phalcon_Db_Column.rst b/pl/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/pl/api/Phalcon_Db_Column.rst +++ b/pl/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/pl/api/Phalcon_Db_Dialect.rst b/pl/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/pl/api/Phalcon_Db_Dialect.rst +++ b/pl/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/pl/api/Phalcon_Db_Dialect_Mysql.rst b/pl/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/pl/api/Phalcon_Db_Dialect_Mysql.rst +++ b/pl/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/pl/api/Phalcon_Db_Dialect_Postgresql.rst b/pl/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/pl/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/pl/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/pl/api/Phalcon_Db_Dialect_Sqlite.rst b/pl/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/pl/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/pl/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/pl/api/Phalcon_Db_Index.rst b/pl/api/Phalcon_Db_Index.rst index 227b766ccbe8..415a456a64bd 100644 --- a/pl/api/Phalcon_Db_Index.rst +++ b/pl/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods diff --git a/pl/api/Phalcon_Db_Profiler.rst b/pl/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/pl/api/Phalcon_Db_Profiler.rst +++ b/pl/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/pl/api/Phalcon_Db_RawValue.rst b/pl/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/pl/api/Phalcon_Db_RawValue.rst +++ b/pl/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/pl/api/Phalcon_Db_Reference.rst b/pl/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/pl/api/Phalcon_Db_Reference.rst +++ b/pl/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/pl/api/Phalcon_Db_Result_Pdo.rst b/pl/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/pl/api/Phalcon_Db_Result_Pdo.rst +++ b/pl/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/pl/api/Phalcon_Debug.rst b/pl/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/pl/api/Phalcon_Debug.rst +++ b/pl/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/pl/api/Phalcon_Debug_Dump.rst b/pl/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/pl/api/Phalcon_Debug_Dump.rst +++ b/pl/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/pl/api/Phalcon_Di.rst b/pl/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/pl/api/Phalcon_Di.rst +++ b/pl/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/pl/api/Phalcon_Di_FactoryDefault.rst b/pl/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/pl/api/Phalcon_Di_FactoryDefault.rst +++ b/pl/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/pl/api/Phalcon_Di_FactoryDefault_Cli.rst b/pl/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/pl/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/pl/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/pl/api/Phalcon_Di_Injectable.rst b/pl/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/pl/api/Phalcon_Di_Injectable.rst +++ b/pl/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/pl/api/Phalcon_Di_Service.rst b/pl/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/pl/api/Phalcon_Di_Service.rst +++ b/pl/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/pl/api/Phalcon_Dispatcher.rst b/pl/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/pl/api/Phalcon_Dispatcher.rst +++ b/pl/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/pl/api/Phalcon_Escaper.rst b/pl/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/pl/api/Phalcon_Escaper.rst +++ b/pl/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/pl/api/Phalcon_Events_Event.rst b/pl/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/pl/api/Phalcon_Events_Event.rst +++ b/pl/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/pl/api/Phalcon_Events_Manager.rst b/pl/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/pl/api/Phalcon_Events_Manager.rst +++ b/pl/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/pl/api/Phalcon_Filter.rst b/pl/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/pl/api/Phalcon_Filter.rst +++ b/pl/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/pl/api/Phalcon_Flash.rst b/pl/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/pl/api/Phalcon_Flash.rst +++ b/pl/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/pl/api/Phalcon_Flash_Direct.rst b/pl/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/pl/api/Phalcon_Flash_Direct.rst +++ b/pl/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/pl/api/Phalcon_Flash_Session.rst b/pl/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/pl/api/Phalcon_Flash_Session.rst +++ b/pl/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/pl/api/Phalcon_Forms_Element.rst b/pl/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/pl/api/Phalcon_Forms_Element.rst +++ b/pl/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_Check.rst b/pl/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/pl/api/Phalcon_Forms_Element_Check.rst +++ b/pl/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_Date.rst b/pl/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/pl/api/Phalcon_Forms_Element_Date.rst +++ b/pl/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_Email.rst b/pl/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/pl/api/Phalcon_Forms_Element_Email.rst +++ b/pl/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_File.rst b/pl/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/pl/api/Phalcon_Forms_Element_File.rst +++ b/pl/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_Hidden.rst b/pl/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/pl/api/Phalcon_Forms_Element_Hidden.rst +++ b/pl/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_Numeric.rst b/pl/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/pl/api/Phalcon_Forms_Element_Numeric.rst +++ b/pl/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_Password.rst b/pl/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/pl/api/Phalcon_Forms_Element_Password.rst +++ b/pl/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_Radio.rst b/pl/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/pl/api/Phalcon_Forms_Element_Radio.rst +++ b/pl/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_Select.rst b/pl/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/pl/api/Phalcon_Forms_Element_Select.rst +++ b/pl/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_Submit.rst b/pl/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/pl/api/Phalcon_Forms_Element_Submit.rst +++ b/pl/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_Text.rst b/pl/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/pl/api/Phalcon_Forms_Element_Text.rst +++ b/pl/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Element_TextArea.rst b/pl/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/pl/api/Phalcon_Forms_Element_TextArea.rst +++ b/pl/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pl/api/Phalcon_Forms_Manager.rst b/pl/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/pl/api/Phalcon_Forms_Manager.rst +++ b/pl/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/pl/api/Phalcon_Http_Cookie.rst b/pl/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/pl/api/Phalcon_Http_Cookie.rst +++ b/pl/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/pl/api/Phalcon_Http_Request.rst b/pl/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/pl/api/Phalcon_Http_Request.rst +++ b/pl/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/pl/api/Phalcon_Http_Request_File.rst b/pl/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/pl/api/Phalcon_Http_Request_File.rst +++ b/pl/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/pl/api/Phalcon_Http_Response.rst b/pl/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/pl/api/Phalcon_Http_Response.rst +++ b/pl/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/pl/api/Phalcon_Http_Response_Cookies.rst b/pl/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/pl/api/Phalcon_Http_Response_Cookies.rst +++ b/pl/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/pl/api/Phalcon_Image_Adapter.rst b/pl/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/pl/api/Phalcon_Image_Adapter.rst +++ b/pl/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/pl/api/Phalcon_Image_Adapter_Gd.rst b/pl/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/pl/api/Phalcon_Image_Adapter_Gd.rst +++ b/pl/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/pl/api/Phalcon_Image_Adapter_Imagick.rst b/pl/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/pl/api/Phalcon_Image_Adapter_Imagick.rst +++ b/pl/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/pl/api/Phalcon_Loader.rst b/pl/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/pl/api/Phalcon_Loader.rst +++ b/pl/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/pl/api/Phalcon_Logger_Adapter.rst b/pl/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/pl/api/Phalcon_Logger_Adapter.rst +++ b/pl/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/pl/api/Phalcon_Logger_Adapter_File.rst b/pl/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/pl/api/Phalcon_Logger_Adapter_File.rst +++ b/pl/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/pl/api/Phalcon_Logger_Adapter_Firephp.rst b/pl/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/pl/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/pl/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/pl/api/Phalcon_Logger_Adapter_Stream.rst b/pl/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/pl/api/Phalcon_Logger_Adapter_Stream.rst +++ b/pl/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/pl/api/Phalcon_Logger_Adapter_Syslog.rst b/pl/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/pl/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/pl/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/pl/api/Phalcon_Mvc_Application.rst b/pl/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/pl/api/Phalcon_Mvc_Application.rst +++ b/pl/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/pl/api/Phalcon_Mvc_Collection.rst b/pl/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/pl/api/Phalcon_Mvc_Collection.rst +++ b/pl/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/pl/api/Phalcon_Mvc_Collection_Behavior.rst b/pl/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/pl/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/pl/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/pl/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/pl/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/pl/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/pl/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/pl/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/pl/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/pl/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/pl/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/pl/api/Phalcon_Mvc_Collection_Document.rst b/pl/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/pl/api/Phalcon_Mvc_Collection_Document.rst +++ b/pl/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/pl/api/Phalcon_Mvc_Collection_Manager.rst b/pl/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/pl/api/Phalcon_Mvc_Collection_Manager.rst +++ b/pl/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/pl/api/Phalcon_Mvc_Controller.rst b/pl/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/pl/api/Phalcon_Mvc_Controller.rst +++ b/pl/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/pl/api/Phalcon_Mvc_Dispatcher.rst b/pl/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/pl/api/Phalcon_Mvc_Dispatcher.rst +++ b/pl/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/pl/api/Phalcon_Mvc_Micro.rst b/pl/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/pl/api/Phalcon_Mvc_Micro.rst +++ b/pl/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/pl/api/Phalcon_Mvc_Model.rst b/pl/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/pl/api/Phalcon_Mvc_Model.rst +++ b/pl/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/pl/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/pl/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/pl/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/pl/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/pl/api/Phalcon_Mvc_Model_Criteria.rst b/pl/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/pl/api/Phalcon_Mvc_Model_Criteria.rst +++ b/pl/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/pl/api/Phalcon_Mvc_Model_Manager.rst b/pl/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/pl/api/Phalcon_Mvc_Model_Manager.rst +++ b/pl/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/pl/api/Phalcon_Mvc_Model_Message.rst b/pl/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/pl/api/Phalcon_Mvc_Model_Message.rst +++ b/pl/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/pl/api/Phalcon_Mvc_Model_MetaData.rst b/pl/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/pl/api/Phalcon_Mvc_Model_MetaData.rst +++ b/pl/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pl/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/pl/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/pl/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/pl/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pl/api/Phalcon_Mvc_Model_MetaData_Files.rst b/pl/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/pl/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/pl/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pl/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/pl/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/pl/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/pl/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/pl/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/pl/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/pl/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/pl/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/pl/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/pl/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/pl/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/pl/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pl/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/pl/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/pl/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/pl/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/pl/api/Phalcon_Mvc_Model_MetaData_Session.rst b/pl/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/pl/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/pl/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pl/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/pl/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/pl/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/pl/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pl/api/Phalcon_Mvc_Model_Query.rst b/pl/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/pl/api/Phalcon_Mvc_Model_Query.rst +++ b/pl/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/pl/api/Phalcon_Mvc_Model_Query_Builder.rst b/pl/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/pl/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/pl/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/pl/api/Phalcon_Mvc_Model_Query_Lang.rst b/pl/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/pl/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/pl/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/pl/api/Phalcon_Mvc_Model_Relation.rst b/pl/api/Phalcon_Mvc_Model_Relation.rst index bbd49acbd3ac..7a0c5587b554 100644 --- a/pl/api/Phalcon_Mvc_Model_Relation.rst +++ b/pl/api/Phalcon_Mvc_Model_Relation.rst @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned diff --git a/pl/api/Phalcon_Mvc_Model_Resultset.rst b/pl/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/pl/api/Phalcon_Mvc_Model_Resultset.rst +++ b/pl/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/pl/api/Phalcon_Mvc_Model_Transaction.rst b/pl/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/pl/api/Phalcon_Mvc_Model_Transaction.rst +++ b/pl/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/pl/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/pl/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/pl/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/pl/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/pl/api/Phalcon_Mvc_Model_ValidationFailed.rst b/pl/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/pl/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/pl/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/pl/api/Phalcon_Mvc_Model_Validator.rst b/pl/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/pl/api/Phalcon_Mvc_Model_Validator_Email.rst b/pl/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pl/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/pl/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pl/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/pl/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pl/api/Phalcon_Mvc_Model_Validator_Ip.rst b/pl/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pl/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/pl/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pl/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/pl/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pl/api/Phalcon_Mvc_Model_Validator_Regex.rst b/pl/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/pl/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/pl/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pl/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/pl/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pl/api/Phalcon_Mvc_Model_Validator_Url.rst b/pl/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/pl/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/pl/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pl/api/Phalcon_Mvc_Router.rst b/pl/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/pl/api/Phalcon_Mvc_Router.rst +++ b/pl/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/pl/api/Phalcon_Mvc_Router_Annotations.rst b/pl/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/pl/api/Phalcon_Mvc_Router_Annotations.rst +++ b/pl/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/pl/api/Phalcon_Mvc_Router_Group.rst b/pl/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/pl/api/Phalcon_Mvc_Router_Group.rst +++ b/pl/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/pl/api/Phalcon_Mvc_Router_Route.rst b/pl/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/pl/api/Phalcon_Mvc_Router_Route.rst +++ b/pl/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/pl/api/Phalcon_Mvc_Url.rst b/pl/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/pl/api/Phalcon_Mvc_Url.rst +++ b/pl/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/pl/api/Phalcon_Mvc_View.rst b/pl/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/pl/api/Phalcon_Mvc_View.rst +++ b/pl/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/pl/api/Phalcon_Mvc_View_Engine.rst b/pl/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/pl/api/Phalcon_Mvc_View_Engine.rst +++ b/pl/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/pl/api/Phalcon_Mvc_View_Engine_Php.rst b/pl/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/pl/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/pl/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/pl/api/Phalcon_Mvc_View_Engine_Volt.rst b/pl/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/pl/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/pl/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/pl/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/pl/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/pl/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/pl/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/pl/api/Phalcon_Mvc_View_Simple.rst b/pl/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/pl/api/Phalcon_Mvc_View_Simple.rst +++ b/pl/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/pl/api/Phalcon_Paginator_Adapter.rst b/pl/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/pl/api/Phalcon_Paginator_Adapter.rst +++ b/pl/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/pl/api/Phalcon_Paginator_Adapter_Model.rst b/pl/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/pl/api/Phalcon_Paginator_Adapter_Model.rst +++ b/pl/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/pl/api/Phalcon_Paginator_Adapter_NativeArray.rst b/pl/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/pl/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/pl/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/pl/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/pl/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/pl/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/pl/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/pl/api/Phalcon_Queue_Beanstalk.rst b/pl/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/pl/api/Phalcon_Queue_Beanstalk.rst +++ b/pl/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/pl/api/Phalcon_Queue_Beanstalk_Job.rst b/pl/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/pl/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/pl/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/pl/api/Phalcon_Registry.rst b/pl/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/pl/api/Phalcon_Registry.rst +++ b/pl/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/pl/api/Phalcon_Security.rst b/pl/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/pl/api/Phalcon_Security.rst +++ b/pl/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/pl/api/Phalcon_Security_Random.rst b/pl/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/pl/api/Phalcon_Security_Random.rst +++ b/pl/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/pl/api/Phalcon_Session_Adapter.rst b/pl/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/pl/api/Phalcon_Session_Adapter.rst +++ b/pl/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/pl/api/Phalcon_Session_Adapter_Files.rst b/pl/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/pl/api/Phalcon_Session_Adapter_Files.rst +++ b/pl/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/pl/api/Phalcon_Session_Adapter_Libmemcached.rst b/pl/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/pl/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/pl/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/pl/api/Phalcon_Session_Adapter_Memcache.rst b/pl/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/pl/api/Phalcon_Session_Adapter_Memcache.rst +++ b/pl/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/pl/api/Phalcon_Session_Adapter_Redis.rst b/pl/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/pl/api/Phalcon_Session_Adapter_Redis.rst +++ b/pl/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/pl/api/Phalcon_Session_Bag.rst b/pl/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/pl/api/Phalcon_Session_Bag.rst +++ b/pl/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/pl/api/Phalcon_Tag.rst b/pl/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/pl/api/Phalcon_Tag.rst +++ b/pl/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/pl/api/Phalcon_Translate_Adapter_Gettext.rst b/pl/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/pl/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/pl/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/pl/api/Phalcon_Validation.rst b/pl/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/pl/api/Phalcon_Validation.rst +++ b/pl/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/pl/api/Phalcon_Validation_CombinedFieldsValidator.rst b/pl/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/pl/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/pl/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Message.rst b/pl/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/pl/api/Phalcon_Validation_Message.rst +++ b/pl/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/pl/api/Phalcon_Validation_Message_Group.rst b/pl/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/pl/api/Phalcon_Validation_Message_Group.rst +++ b/pl/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/pl/api/Phalcon_Validation_Validator.rst b/pl/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/pl/api/Phalcon_Validation_Validator.rst +++ b/pl/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Alnum.rst b/pl/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/pl/api/Phalcon_Validation_Validator_Alnum.rst +++ b/pl/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Alpha.rst b/pl/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/pl/api/Phalcon_Validation_Validator_Alpha.rst +++ b/pl/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Between.rst b/pl/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/pl/api/Phalcon_Validation_Validator_Between.rst +++ b/pl/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Confirmation.rst b/pl/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/pl/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/pl/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_CreditCard.rst b/pl/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/pl/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/pl/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Date.rst b/pl/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/pl/api/Phalcon_Validation_Validator_Date.rst +++ b/pl/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Digit.rst b/pl/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/pl/api/Phalcon_Validation_Validator_Digit.rst +++ b/pl/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Email.rst b/pl/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/pl/api/Phalcon_Validation_Validator_Email.rst +++ b/pl/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_ExclusionIn.rst b/pl/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/pl/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/pl/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_File.rst b/pl/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/pl/api/Phalcon_Validation_Validator_File.rst +++ b/pl/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Identical.rst b/pl/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/pl/api/Phalcon_Validation_Validator_Identical.rst +++ b/pl/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_InclusionIn.rst b/pl/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/pl/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/pl/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Numericality.rst b/pl/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/pl/api/Phalcon_Validation_Validator_Numericality.rst +++ b/pl/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_PresenceOf.rst b/pl/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/pl/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/pl/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Regex.rst b/pl/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/pl/api/Phalcon_Validation_Validator_Regex.rst +++ b/pl/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_StringLength.rst b/pl/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/pl/api/Phalcon_Validation_Validator_StringLength.rst +++ b/pl/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Uniqueness.rst b/pl/api/Phalcon_Validation_Validator_Uniqueness.rst index af0bde58d45d..8af5174ddfba 100644 --- a/pl/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/pl/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,59 +10,84 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; - Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); - In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); + $validator->add( + "username", + new UniquenessValidator() + ); - Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); - It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); @@ -106,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Validation_Validator_Url.rst b/pl/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/pl/api/Phalcon_Validation_Validator_Url.rst +++ b/pl/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pl/api/Phalcon_Version.rst b/pl/api/Phalcon_Version.rst index 4322c6cb17bb..77d94d7b0e5a 100644 --- a/pl/api/Phalcon_Version.rst +++ b/pl/api/Phalcon_Version.rst @@ -27,51 +27,61 @@ 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. +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. final protected static **_getSpecial** (*mixed* $special) -Translates a number to a special release If Special release = 1 this function will return ALPHA +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -Returns the active version (string) +Returns the active version (string) .. code-block:: php Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/pt/api/Phalcon_Annotations_Adapter_Apc.rst b/pt/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/pt/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/pt/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/pt/api/Phalcon_Annotations_Adapter_Files.rst b/pt/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/pt/api/Phalcon_Annotations_Adapter_Files.rst +++ b/pt/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/pt/api/Phalcon_Annotations_Adapter_Memory.rst b/pt/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/pt/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/pt/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/pt/api/Phalcon_Annotations_Adapter_Xcache.rst b/pt/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/pt/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/pt/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/pt/api/Phalcon_Annotations_Reflection.rst b/pt/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/pt/api/Phalcon_Annotations_Reflection.rst +++ b/pt/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/pt/api/Phalcon_Application.rst b/pt/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/pt/api/Phalcon_Application.rst +++ b/pt/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/pt/api/Phalcon_Assets_Filters_Cssmin.rst b/pt/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/pt/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/pt/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/pt/api/Phalcon_Assets_Filters_Jsmin.rst b/pt/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/pt/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/pt/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/pt/api/Phalcon_Assets_Inline.rst b/pt/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/pt/api/Phalcon_Assets_Inline.rst +++ b/pt/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/pt/api/Phalcon_Assets_Resource.rst b/pt/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/pt/api/Phalcon_Assets_Resource.rst +++ b/pt/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/pt/api/Phalcon_Assets_Resource_Js.rst b/pt/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/pt/api/Phalcon_Assets_Resource_Js.rst +++ b/pt/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/pt/api/Phalcon_Cache_Backend.rst b/pt/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/pt/api/Phalcon_Cache_Backend.rst +++ b/pt/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/pt/api/Phalcon_Cache_Backend_Apc.rst b/pt/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/pt/api/Phalcon_Cache_Backend_Apc.rst +++ b/pt/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/pt/api/Phalcon_Cache_Backend_File.rst b/pt/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/pt/api/Phalcon_Cache_Backend_File.rst +++ b/pt/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/pt/api/Phalcon_Cache_Backend_Libmemcached.rst b/pt/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/pt/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/pt/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/pt/api/Phalcon_Cache_Backend_Memcache.rst b/pt/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/pt/api/Phalcon_Cache_Backend_Memcache.rst +++ b/pt/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/pt/api/Phalcon_Cache_Backend_Memory.rst b/pt/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/pt/api/Phalcon_Cache_Backend_Memory.rst +++ b/pt/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/pt/api/Phalcon_Cache_Backend_Mongo.rst b/pt/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/pt/api/Phalcon_Cache_Backend_Mongo.rst +++ b/pt/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/pt/api/Phalcon_Cache_Backend_Redis.rst b/pt/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/pt/api/Phalcon_Cache_Backend_Redis.rst +++ b/pt/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/pt/api/Phalcon_Cache_Backend_Xcache.rst b/pt/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/pt/api/Phalcon_Cache_Backend_Xcache.rst +++ b/pt/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/pt/api/Phalcon_Cache_Frontend_Base64.rst b/pt/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/pt/api/Phalcon_Cache_Frontend_Base64.rst +++ b/pt/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/pt/api/Phalcon_Cache_Frontend_Data.rst b/pt/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/pt/api/Phalcon_Cache_Frontend_Data.rst +++ b/pt/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/pt/api/Phalcon_Cache_Frontend_Igbinary.rst b/pt/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/pt/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/pt/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/pt/api/Phalcon_Cache_Frontend_Json.rst b/pt/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/pt/api/Phalcon_Cache_Frontend_Json.rst +++ b/pt/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/pt/api/Phalcon_Cache_Frontend_Msgpack.rst b/pt/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/pt/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/pt/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/pt/api/Phalcon_Cache_Frontend_None.rst b/pt/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/pt/api/Phalcon_Cache_Frontend_None.rst +++ b/pt/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/pt/api/Phalcon_Cache_Frontend_Output.rst b/pt/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/pt/api/Phalcon_Cache_Frontend_Output.rst +++ b/pt/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/pt/api/Phalcon_Cache_Multiple.rst b/pt/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/pt/api/Phalcon_Cache_Multiple.rst +++ b/pt/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/pt/api/Phalcon_Cli_Console.rst b/pt/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/pt/api/Phalcon_Cli_Console.rst +++ b/pt/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/pt/api/Phalcon_Cli_Dispatcher.rst b/pt/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/pt/api/Phalcon_Cli_Dispatcher.rst +++ b/pt/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/pt/api/Phalcon_Cli_Router.rst b/pt/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/pt/api/Phalcon_Cli_Router.rst +++ b/pt/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/pt/api/Phalcon_Cli_Router_Route.rst b/pt/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/pt/api/Phalcon_Cli_Router_Route.rst +++ b/pt/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/pt/api/Phalcon_Cli_Task.rst b/pt/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/pt/api/Phalcon_Cli_Task.rst +++ b/pt/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/pt/api/Phalcon_Config.rst b/pt/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/pt/api/Phalcon_Config.rst +++ b/pt/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/pt/api/Phalcon_Config_Adapter_Ini.rst b/pt/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/pt/api/Phalcon_Config_Adapter_Ini.rst +++ b/pt/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/pt/api/Phalcon_Config_Adapter_Json.rst b/pt/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/pt/api/Phalcon_Config_Adapter_Json.rst +++ b/pt/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/pt/api/Phalcon_Config_Adapter_Php.rst b/pt/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/pt/api/Phalcon_Config_Adapter_Php.rst +++ b/pt/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/pt/api/Phalcon_Config_Adapter_Yaml.rst b/pt/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/pt/api/Phalcon_Config_Adapter_Yaml.rst +++ b/pt/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/pt/api/Phalcon_Crypt.rst b/pt/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/pt/api/Phalcon_Crypt.rst +++ b/pt/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/pt/api/Phalcon_Db.rst b/pt/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/pt/api/Phalcon_Db.rst +++ b/pt/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/pt/api/Phalcon_Db_Adapter.rst b/pt/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/pt/api/Phalcon_Db_Adapter.rst +++ b/pt/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/pt/api/Phalcon_Db_Adapter_Pdo.rst b/pt/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/pt/api/Phalcon_Db_Adapter_Pdo.rst +++ b/pt/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/pt/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/pt/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/pt/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/pt/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/pt/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/pt/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/pt/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/pt/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/pt/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/pt/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/pt/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/pt/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/pt/api/Phalcon_Db_Column.rst b/pt/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/pt/api/Phalcon_Db_Column.rst +++ b/pt/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/pt/api/Phalcon_Db_Dialect.rst b/pt/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/pt/api/Phalcon_Db_Dialect.rst +++ b/pt/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/pt/api/Phalcon_Db_Dialect_Mysql.rst b/pt/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/pt/api/Phalcon_Db_Dialect_Mysql.rst +++ b/pt/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/pt/api/Phalcon_Db_Dialect_Postgresql.rst b/pt/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/pt/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/pt/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/pt/api/Phalcon_Db_Dialect_Sqlite.rst b/pt/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/pt/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/pt/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/pt/api/Phalcon_Db_Index.rst b/pt/api/Phalcon_Db_Index.rst index 227b766ccbe8..415a456a64bd 100644 --- a/pt/api/Phalcon_Db_Index.rst +++ b/pt/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods diff --git a/pt/api/Phalcon_Db_Profiler.rst b/pt/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/pt/api/Phalcon_Db_Profiler.rst +++ b/pt/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/pt/api/Phalcon_Db_RawValue.rst b/pt/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/pt/api/Phalcon_Db_RawValue.rst +++ b/pt/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/pt/api/Phalcon_Db_Reference.rst b/pt/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/pt/api/Phalcon_Db_Reference.rst +++ b/pt/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/pt/api/Phalcon_Db_Result_Pdo.rst b/pt/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/pt/api/Phalcon_Db_Result_Pdo.rst +++ b/pt/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/pt/api/Phalcon_Debug.rst b/pt/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/pt/api/Phalcon_Debug.rst +++ b/pt/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/pt/api/Phalcon_Debug_Dump.rst b/pt/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/pt/api/Phalcon_Debug_Dump.rst +++ b/pt/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/pt/api/Phalcon_Di.rst b/pt/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/pt/api/Phalcon_Di.rst +++ b/pt/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/pt/api/Phalcon_Di_FactoryDefault.rst b/pt/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/pt/api/Phalcon_Di_FactoryDefault.rst +++ b/pt/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/pt/api/Phalcon_Di_FactoryDefault_Cli.rst b/pt/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/pt/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/pt/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/pt/api/Phalcon_Di_Injectable.rst b/pt/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/pt/api/Phalcon_Di_Injectable.rst +++ b/pt/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/pt/api/Phalcon_Di_Service.rst b/pt/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/pt/api/Phalcon_Di_Service.rst +++ b/pt/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/pt/api/Phalcon_Dispatcher.rst b/pt/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/pt/api/Phalcon_Dispatcher.rst +++ b/pt/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/pt/api/Phalcon_Escaper.rst b/pt/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/pt/api/Phalcon_Escaper.rst +++ b/pt/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/pt/api/Phalcon_Events_Event.rst b/pt/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/pt/api/Phalcon_Events_Event.rst +++ b/pt/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/pt/api/Phalcon_Events_Manager.rst b/pt/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/pt/api/Phalcon_Events_Manager.rst +++ b/pt/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/pt/api/Phalcon_Filter.rst b/pt/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/pt/api/Phalcon_Filter.rst +++ b/pt/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/pt/api/Phalcon_Flash.rst b/pt/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/pt/api/Phalcon_Flash.rst +++ b/pt/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/pt/api/Phalcon_Flash_Direct.rst b/pt/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/pt/api/Phalcon_Flash_Direct.rst +++ b/pt/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/pt/api/Phalcon_Flash_Session.rst b/pt/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/pt/api/Phalcon_Flash_Session.rst +++ b/pt/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/pt/api/Phalcon_Forms_Element.rst b/pt/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/pt/api/Phalcon_Forms_Element.rst +++ b/pt/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_Check.rst b/pt/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/pt/api/Phalcon_Forms_Element_Check.rst +++ b/pt/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_Date.rst b/pt/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/pt/api/Phalcon_Forms_Element_Date.rst +++ b/pt/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_Email.rst b/pt/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/pt/api/Phalcon_Forms_Element_Email.rst +++ b/pt/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_File.rst b/pt/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/pt/api/Phalcon_Forms_Element_File.rst +++ b/pt/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_Hidden.rst b/pt/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/pt/api/Phalcon_Forms_Element_Hidden.rst +++ b/pt/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_Numeric.rst b/pt/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/pt/api/Phalcon_Forms_Element_Numeric.rst +++ b/pt/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_Password.rst b/pt/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/pt/api/Phalcon_Forms_Element_Password.rst +++ b/pt/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_Radio.rst b/pt/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/pt/api/Phalcon_Forms_Element_Radio.rst +++ b/pt/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_Select.rst b/pt/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/pt/api/Phalcon_Forms_Element_Select.rst +++ b/pt/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_Submit.rst b/pt/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/pt/api/Phalcon_Forms_Element_Submit.rst +++ b/pt/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_Text.rst b/pt/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/pt/api/Phalcon_Forms_Element_Text.rst +++ b/pt/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Element_TextArea.rst b/pt/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/pt/api/Phalcon_Forms_Element_TextArea.rst +++ b/pt/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/pt/api/Phalcon_Forms_Manager.rst b/pt/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/pt/api/Phalcon_Forms_Manager.rst +++ b/pt/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/pt/api/Phalcon_Http_Cookie.rst b/pt/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/pt/api/Phalcon_Http_Cookie.rst +++ b/pt/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/pt/api/Phalcon_Http_Request.rst b/pt/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/pt/api/Phalcon_Http_Request.rst +++ b/pt/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/pt/api/Phalcon_Http_Request_File.rst b/pt/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/pt/api/Phalcon_Http_Request_File.rst +++ b/pt/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/pt/api/Phalcon_Http_Response.rst b/pt/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/pt/api/Phalcon_Http_Response.rst +++ b/pt/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/pt/api/Phalcon_Http_Response_Cookies.rst b/pt/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/pt/api/Phalcon_Http_Response_Cookies.rst +++ b/pt/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/pt/api/Phalcon_Image_Adapter.rst b/pt/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/pt/api/Phalcon_Image_Adapter.rst +++ b/pt/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/pt/api/Phalcon_Image_Adapter_Gd.rst b/pt/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/pt/api/Phalcon_Image_Adapter_Gd.rst +++ b/pt/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/pt/api/Phalcon_Image_Adapter_Imagick.rst b/pt/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/pt/api/Phalcon_Image_Adapter_Imagick.rst +++ b/pt/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/pt/api/Phalcon_Loader.rst b/pt/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/pt/api/Phalcon_Loader.rst +++ b/pt/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/pt/api/Phalcon_Logger_Adapter.rst b/pt/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/pt/api/Phalcon_Logger_Adapter.rst +++ b/pt/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/pt/api/Phalcon_Logger_Adapter_File.rst b/pt/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/pt/api/Phalcon_Logger_Adapter_File.rst +++ b/pt/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/pt/api/Phalcon_Logger_Adapter_Firephp.rst b/pt/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/pt/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/pt/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/pt/api/Phalcon_Logger_Adapter_Stream.rst b/pt/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/pt/api/Phalcon_Logger_Adapter_Stream.rst +++ b/pt/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/pt/api/Phalcon_Logger_Adapter_Syslog.rst b/pt/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/pt/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/pt/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/pt/api/Phalcon_Mvc_Application.rst b/pt/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/pt/api/Phalcon_Mvc_Application.rst +++ b/pt/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/pt/api/Phalcon_Mvc_Collection.rst b/pt/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/pt/api/Phalcon_Mvc_Collection.rst +++ b/pt/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/pt/api/Phalcon_Mvc_Collection_Behavior.rst b/pt/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/pt/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/pt/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/pt/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/pt/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/pt/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/pt/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/pt/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/pt/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/pt/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/pt/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/pt/api/Phalcon_Mvc_Collection_Document.rst b/pt/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/pt/api/Phalcon_Mvc_Collection_Document.rst +++ b/pt/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/pt/api/Phalcon_Mvc_Collection_Manager.rst b/pt/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/pt/api/Phalcon_Mvc_Collection_Manager.rst +++ b/pt/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/pt/api/Phalcon_Mvc_Controller.rst b/pt/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/pt/api/Phalcon_Mvc_Controller.rst +++ b/pt/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/pt/api/Phalcon_Mvc_Dispatcher.rst b/pt/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/pt/api/Phalcon_Mvc_Dispatcher.rst +++ b/pt/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/pt/api/Phalcon_Mvc_Micro.rst b/pt/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/pt/api/Phalcon_Mvc_Micro.rst +++ b/pt/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/pt/api/Phalcon_Mvc_Model.rst b/pt/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/pt/api/Phalcon_Mvc_Model.rst +++ b/pt/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/pt/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/pt/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/pt/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/pt/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/pt/api/Phalcon_Mvc_Model_Criteria.rst b/pt/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/pt/api/Phalcon_Mvc_Model_Criteria.rst +++ b/pt/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/pt/api/Phalcon_Mvc_Model_Manager.rst b/pt/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/pt/api/Phalcon_Mvc_Model_Manager.rst +++ b/pt/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/pt/api/Phalcon_Mvc_Model_Message.rst b/pt/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/pt/api/Phalcon_Mvc_Model_Message.rst +++ b/pt/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/pt/api/Phalcon_Mvc_Model_MetaData.rst b/pt/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/pt/api/Phalcon_Mvc_Model_MetaData.rst +++ b/pt/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pt/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/pt/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/pt/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/pt/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pt/api/Phalcon_Mvc_Model_MetaData_Files.rst b/pt/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/pt/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/pt/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pt/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/pt/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/pt/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/pt/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/pt/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/pt/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/pt/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/pt/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/pt/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/pt/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/pt/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/pt/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pt/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/pt/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/pt/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/pt/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/pt/api/Phalcon_Mvc_Model_MetaData_Session.rst b/pt/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/pt/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/pt/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pt/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/pt/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/pt/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/pt/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/pt/api/Phalcon_Mvc_Model_Query.rst b/pt/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/pt/api/Phalcon_Mvc_Model_Query.rst +++ b/pt/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/pt/api/Phalcon_Mvc_Model_Query_Builder.rst b/pt/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/pt/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/pt/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/pt/api/Phalcon_Mvc_Model_Query_Lang.rst b/pt/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/pt/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/pt/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/pt/api/Phalcon_Mvc_Model_Relation.rst b/pt/api/Phalcon_Mvc_Model_Relation.rst index bbd49acbd3ac..7a0c5587b554 100644 --- a/pt/api/Phalcon_Mvc_Model_Relation.rst +++ b/pt/api/Phalcon_Mvc_Model_Relation.rst @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned diff --git a/pt/api/Phalcon_Mvc_Model_Resultset.rst b/pt/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/pt/api/Phalcon_Mvc_Model_Resultset.rst +++ b/pt/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/pt/api/Phalcon_Mvc_Model_Transaction.rst b/pt/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/pt/api/Phalcon_Mvc_Model_Transaction.rst +++ b/pt/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/pt/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/pt/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/pt/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/pt/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/pt/api/Phalcon_Mvc_Model_ValidationFailed.rst b/pt/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/pt/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/pt/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/pt/api/Phalcon_Mvc_Model_Validator.rst b/pt/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/pt/api/Phalcon_Mvc_Model_Validator_Email.rst b/pt/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pt/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/pt/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pt/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/pt/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pt/api/Phalcon_Mvc_Model_Validator_Ip.rst b/pt/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pt/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/pt/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pt/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/pt/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pt/api/Phalcon_Mvc_Model_Validator_Regex.rst b/pt/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/pt/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/pt/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pt/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/pt/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pt/api/Phalcon_Mvc_Model_Validator_Url.rst b/pt/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/pt/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/pt/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/pt/api/Phalcon_Mvc_Router.rst b/pt/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/pt/api/Phalcon_Mvc_Router.rst +++ b/pt/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/pt/api/Phalcon_Mvc_Router_Annotations.rst b/pt/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/pt/api/Phalcon_Mvc_Router_Annotations.rst +++ b/pt/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/pt/api/Phalcon_Mvc_Router_Group.rst b/pt/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/pt/api/Phalcon_Mvc_Router_Group.rst +++ b/pt/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/pt/api/Phalcon_Mvc_Router_Route.rst b/pt/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/pt/api/Phalcon_Mvc_Router_Route.rst +++ b/pt/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/pt/api/Phalcon_Mvc_Url.rst b/pt/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/pt/api/Phalcon_Mvc_Url.rst +++ b/pt/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/pt/api/Phalcon_Mvc_View.rst b/pt/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/pt/api/Phalcon_Mvc_View.rst +++ b/pt/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/pt/api/Phalcon_Mvc_View_Engine.rst b/pt/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/pt/api/Phalcon_Mvc_View_Engine.rst +++ b/pt/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/pt/api/Phalcon_Mvc_View_Engine_Php.rst b/pt/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/pt/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/pt/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/pt/api/Phalcon_Mvc_View_Engine_Volt.rst b/pt/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/pt/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/pt/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/pt/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/pt/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/pt/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/pt/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/pt/api/Phalcon_Mvc_View_Simple.rst b/pt/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/pt/api/Phalcon_Mvc_View_Simple.rst +++ b/pt/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/pt/api/Phalcon_Paginator_Adapter.rst b/pt/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/pt/api/Phalcon_Paginator_Adapter.rst +++ b/pt/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/pt/api/Phalcon_Paginator_Adapter_Model.rst b/pt/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/pt/api/Phalcon_Paginator_Adapter_Model.rst +++ b/pt/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/pt/api/Phalcon_Paginator_Adapter_NativeArray.rst b/pt/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/pt/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/pt/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/pt/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/pt/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/pt/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/pt/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/pt/api/Phalcon_Queue_Beanstalk.rst b/pt/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/pt/api/Phalcon_Queue_Beanstalk.rst +++ b/pt/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/pt/api/Phalcon_Queue_Beanstalk_Job.rst b/pt/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/pt/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/pt/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/pt/api/Phalcon_Registry.rst b/pt/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/pt/api/Phalcon_Registry.rst +++ b/pt/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/pt/api/Phalcon_Security.rst b/pt/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/pt/api/Phalcon_Security.rst +++ b/pt/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/pt/api/Phalcon_Security_Random.rst b/pt/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/pt/api/Phalcon_Security_Random.rst +++ b/pt/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/pt/api/Phalcon_Session_Adapter.rst b/pt/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/pt/api/Phalcon_Session_Adapter.rst +++ b/pt/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/pt/api/Phalcon_Session_Adapter_Files.rst b/pt/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/pt/api/Phalcon_Session_Adapter_Files.rst +++ b/pt/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/pt/api/Phalcon_Session_Adapter_Libmemcached.rst b/pt/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/pt/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/pt/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/pt/api/Phalcon_Session_Adapter_Memcache.rst b/pt/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/pt/api/Phalcon_Session_Adapter_Memcache.rst +++ b/pt/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/pt/api/Phalcon_Session_Adapter_Redis.rst b/pt/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/pt/api/Phalcon_Session_Adapter_Redis.rst +++ b/pt/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/pt/api/Phalcon_Session_Bag.rst b/pt/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/pt/api/Phalcon_Session_Bag.rst +++ b/pt/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/pt/api/Phalcon_Tag.rst b/pt/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/pt/api/Phalcon_Tag.rst +++ b/pt/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/pt/api/Phalcon_Translate_Adapter_Gettext.rst b/pt/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/pt/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/pt/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/pt/api/Phalcon_Validation.rst b/pt/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/pt/api/Phalcon_Validation.rst +++ b/pt/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/pt/api/Phalcon_Validation_CombinedFieldsValidator.rst b/pt/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/pt/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/pt/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Message.rst b/pt/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/pt/api/Phalcon_Validation_Message.rst +++ b/pt/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/pt/api/Phalcon_Validation_Message_Group.rst b/pt/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/pt/api/Phalcon_Validation_Message_Group.rst +++ b/pt/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/pt/api/Phalcon_Validation_Validator.rst b/pt/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/pt/api/Phalcon_Validation_Validator.rst +++ b/pt/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Alnum.rst b/pt/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/pt/api/Phalcon_Validation_Validator_Alnum.rst +++ b/pt/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Alpha.rst b/pt/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/pt/api/Phalcon_Validation_Validator_Alpha.rst +++ b/pt/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Between.rst b/pt/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/pt/api/Phalcon_Validation_Validator_Between.rst +++ b/pt/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Confirmation.rst b/pt/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/pt/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/pt/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_CreditCard.rst b/pt/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/pt/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/pt/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Date.rst b/pt/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/pt/api/Phalcon_Validation_Validator_Date.rst +++ b/pt/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Digit.rst b/pt/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/pt/api/Phalcon_Validation_Validator_Digit.rst +++ b/pt/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Email.rst b/pt/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/pt/api/Phalcon_Validation_Validator_Email.rst +++ b/pt/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_ExclusionIn.rst b/pt/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/pt/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/pt/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_File.rst b/pt/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/pt/api/Phalcon_Validation_Validator_File.rst +++ b/pt/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Identical.rst b/pt/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/pt/api/Phalcon_Validation_Validator_Identical.rst +++ b/pt/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_InclusionIn.rst b/pt/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/pt/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/pt/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Numericality.rst b/pt/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/pt/api/Phalcon_Validation_Validator_Numericality.rst +++ b/pt/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_PresenceOf.rst b/pt/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/pt/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/pt/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Regex.rst b/pt/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/pt/api/Phalcon_Validation_Validator_Regex.rst +++ b/pt/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_StringLength.rst b/pt/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/pt/api/Phalcon_Validation_Validator_StringLength.rst +++ b/pt/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Uniqueness.rst b/pt/api/Phalcon_Validation_Validator_Uniqueness.rst index af0bde58d45d..8af5174ddfba 100644 --- a/pt/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/pt/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,59 +10,84 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; - Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); - In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); + $validator->add( + "username", + new UniquenessValidator() + ); - Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); - It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); @@ -106,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Validation_Validator_Url.rst b/pt/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/pt/api/Phalcon_Validation_Validator_Url.rst +++ b/pt/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/pt/api/Phalcon_Version.rst b/pt/api/Phalcon_Version.rst index 4322c6cb17bb..77d94d7b0e5a 100644 --- a/pt/api/Phalcon_Version.rst +++ b/pt/api/Phalcon_Version.rst @@ -27,51 +27,61 @@ 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. +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. final protected static **_getSpecial** (*mixed* $special) -Translates a number to a special release If Special release = 1 this function will return ALPHA +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -Returns the active version (string) +Returns the active version (string) .. code-block:: php Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/ru/api/Phalcon_Annotations_Adapter_Apc.rst b/ru/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/ru/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/ru/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/ru/api/Phalcon_Annotations_Adapter_Files.rst b/ru/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/ru/api/Phalcon_Annotations_Adapter_Files.rst +++ b/ru/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/ru/api/Phalcon_Annotations_Adapter_Memory.rst b/ru/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/ru/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/ru/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/ru/api/Phalcon_Annotations_Adapter_Xcache.rst b/ru/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/ru/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/ru/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/ru/api/Phalcon_Annotations_Reflection.rst b/ru/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/ru/api/Phalcon_Annotations_Reflection.rst +++ b/ru/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/ru/api/Phalcon_Application.rst b/ru/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/ru/api/Phalcon_Application.rst +++ b/ru/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/ru/api/Phalcon_Assets_Filters_Cssmin.rst b/ru/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/ru/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/ru/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/ru/api/Phalcon_Assets_Filters_Jsmin.rst b/ru/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/ru/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/ru/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/ru/api/Phalcon_Assets_Inline.rst b/ru/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/ru/api/Phalcon_Assets_Inline.rst +++ b/ru/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/ru/api/Phalcon_Assets_Resource.rst b/ru/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/ru/api/Phalcon_Assets_Resource.rst +++ b/ru/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/ru/api/Phalcon_Assets_Resource_Js.rst b/ru/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/ru/api/Phalcon_Assets_Resource_Js.rst +++ b/ru/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/ru/api/Phalcon_Cache_Backend.rst b/ru/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/ru/api/Phalcon_Cache_Backend.rst +++ b/ru/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/ru/api/Phalcon_Cache_Backend_Apc.rst b/ru/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/ru/api/Phalcon_Cache_Backend_Apc.rst +++ b/ru/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/ru/api/Phalcon_Cache_Backend_File.rst b/ru/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/ru/api/Phalcon_Cache_Backend_File.rst +++ b/ru/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/ru/api/Phalcon_Cache_Backend_Libmemcached.rst b/ru/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/ru/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/ru/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/ru/api/Phalcon_Cache_Backend_Memcache.rst b/ru/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/ru/api/Phalcon_Cache_Backend_Memcache.rst +++ b/ru/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/ru/api/Phalcon_Cache_Backend_Memory.rst b/ru/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/ru/api/Phalcon_Cache_Backend_Memory.rst +++ b/ru/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/ru/api/Phalcon_Cache_Backend_Mongo.rst b/ru/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/ru/api/Phalcon_Cache_Backend_Mongo.rst +++ b/ru/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/ru/api/Phalcon_Cache_Backend_Redis.rst b/ru/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/ru/api/Phalcon_Cache_Backend_Redis.rst +++ b/ru/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/ru/api/Phalcon_Cache_Backend_Xcache.rst b/ru/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/ru/api/Phalcon_Cache_Backend_Xcache.rst +++ b/ru/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/ru/api/Phalcon_Cache_Frontend_Base64.rst b/ru/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/ru/api/Phalcon_Cache_Frontend_Base64.rst +++ b/ru/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/ru/api/Phalcon_Cache_Frontend_Data.rst b/ru/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/ru/api/Phalcon_Cache_Frontend_Data.rst +++ b/ru/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/ru/api/Phalcon_Cache_Frontend_Igbinary.rst b/ru/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/ru/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/ru/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/ru/api/Phalcon_Cache_Frontend_Json.rst b/ru/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/ru/api/Phalcon_Cache_Frontend_Json.rst +++ b/ru/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/ru/api/Phalcon_Cache_Frontend_Msgpack.rst b/ru/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/ru/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/ru/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/ru/api/Phalcon_Cache_Frontend_None.rst b/ru/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/ru/api/Phalcon_Cache_Frontend_None.rst +++ b/ru/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/ru/api/Phalcon_Cache_Frontend_Output.rst b/ru/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/ru/api/Phalcon_Cache_Frontend_Output.rst +++ b/ru/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/ru/api/Phalcon_Cache_Multiple.rst b/ru/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/ru/api/Phalcon_Cache_Multiple.rst +++ b/ru/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/ru/api/Phalcon_Cli_Console.rst b/ru/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/ru/api/Phalcon_Cli_Console.rst +++ b/ru/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/ru/api/Phalcon_Cli_Dispatcher.rst b/ru/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/ru/api/Phalcon_Cli_Dispatcher.rst +++ b/ru/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/ru/api/Phalcon_Cli_Router.rst b/ru/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/ru/api/Phalcon_Cli_Router.rst +++ b/ru/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/ru/api/Phalcon_Cli_Router_Route.rst b/ru/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/ru/api/Phalcon_Cli_Router_Route.rst +++ b/ru/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/ru/api/Phalcon_Cli_Task.rst b/ru/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/ru/api/Phalcon_Cli_Task.rst +++ b/ru/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/ru/api/Phalcon_Config.rst b/ru/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/ru/api/Phalcon_Config.rst +++ b/ru/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/ru/api/Phalcon_Config_Adapter_Ini.rst b/ru/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/ru/api/Phalcon_Config_Adapter_Ini.rst +++ b/ru/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/ru/api/Phalcon_Config_Adapter_Json.rst b/ru/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/ru/api/Phalcon_Config_Adapter_Json.rst +++ b/ru/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/ru/api/Phalcon_Config_Adapter_Php.rst b/ru/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/ru/api/Phalcon_Config_Adapter_Php.rst +++ b/ru/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/ru/api/Phalcon_Config_Adapter_Yaml.rst b/ru/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/ru/api/Phalcon_Config_Adapter_Yaml.rst +++ b/ru/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/ru/api/Phalcon_Crypt.rst b/ru/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/ru/api/Phalcon_Crypt.rst +++ b/ru/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/ru/api/Phalcon_Db.rst b/ru/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/ru/api/Phalcon_Db.rst +++ b/ru/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/ru/api/Phalcon_Db_Adapter.rst b/ru/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/ru/api/Phalcon_Db_Adapter.rst +++ b/ru/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/ru/api/Phalcon_Db_Adapter_Pdo.rst b/ru/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/ru/api/Phalcon_Db_Adapter_Pdo.rst +++ b/ru/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/ru/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/ru/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/ru/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/ru/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/ru/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/ru/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/ru/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/ru/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/ru/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/ru/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/ru/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/ru/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/ru/api/Phalcon_Db_Column.rst b/ru/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/ru/api/Phalcon_Db_Column.rst +++ b/ru/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/ru/api/Phalcon_Db_Dialect.rst b/ru/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/ru/api/Phalcon_Db_Dialect.rst +++ b/ru/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/ru/api/Phalcon_Db_Dialect_Mysql.rst b/ru/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/ru/api/Phalcon_Db_Dialect_Mysql.rst +++ b/ru/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/ru/api/Phalcon_Db_Dialect_Postgresql.rst b/ru/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/ru/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/ru/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/ru/api/Phalcon_Db_Dialect_Sqlite.rst b/ru/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/ru/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/ru/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/ru/api/Phalcon_Db_Index.rst b/ru/api/Phalcon_Db_Index.rst index 227b766ccbe8..415a456a64bd 100644 --- a/ru/api/Phalcon_Db_Index.rst +++ b/ru/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods diff --git a/ru/api/Phalcon_Db_Profiler.rst b/ru/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/ru/api/Phalcon_Db_Profiler.rst +++ b/ru/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/ru/api/Phalcon_Db_RawValue.rst b/ru/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/ru/api/Phalcon_Db_RawValue.rst +++ b/ru/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/ru/api/Phalcon_Db_Reference.rst b/ru/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/ru/api/Phalcon_Db_Reference.rst +++ b/ru/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/ru/api/Phalcon_Db_Result_Pdo.rst b/ru/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/ru/api/Phalcon_Db_Result_Pdo.rst +++ b/ru/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/ru/api/Phalcon_Debug.rst b/ru/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/ru/api/Phalcon_Debug.rst +++ b/ru/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/ru/api/Phalcon_Debug_Dump.rst b/ru/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/ru/api/Phalcon_Debug_Dump.rst +++ b/ru/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/ru/api/Phalcon_Di.rst b/ru/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/ru/api/Phalcon_Di.rst +++ b/ru/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/ru/api/Phalcon_Di_FactoryDefault.rst b/ru/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/ru/api/Phalcon_Di_FactoryDefault.rst +++ b/ru/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/ru/api/Phalcon_Di_FactoryDefault_Cli.rst b/ru/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/ru/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/ru/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/ru/api/Phalcon_Di_Injectable.rst b/ru/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/ru/api/Phalcon_Di_Injectable.rst +++ b/ru/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/ru/api/Phalcon_Di_Service.rst b/ru/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/ru/api/Phalcon_Di_Service.rst +++ b/ru/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/ru/api/Phalcon_Dispatcher.rst b/ru/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/ru/api/Phalcon_Dispatcher.rst +++ b/ru/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/ru/api/Phalcon_Escaper.rst b/ru/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/ru/api/Phalcon_Escaper.rst +++ b/ru/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/ru/api/Phalcon_Events_Event.rst b/ru/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/ru/api/Phalcon_Events_Event.rst +++ b/ru/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/ru/api/Phalcon_Events_Manager.rst b/ru/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/ru/api/Phalcon_Events_Manager.rst +++ b/ru/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/ru/api/Phalcon_Filter.rst b/ru/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/ru/api/Phalcon_Filter.rst +++ b/ru/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/ru/api/Phalcon_Flash.rst b/ru/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/ru/api/Phalcon_Flash.rst +++ b/ru/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/ru/api/Phalcon_Flash_Direct.rst b/ru/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/ru/api/Phalcon_Flash_Direct.rst +++ b/ru/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/ru/api/Phalcon_Flash_Session.rst b/ru/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/ru/api/Phalcon_Flash_Session.rst +++ b/ru/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/ru/api/Phalcon_Forms_Element.rst b/ru/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/ru/api/Phalcon_Forms_Element.rst +++ b/ru/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_Check.rst b/ru/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/ru/api/Phalcon_Forms_Element_Check.rst +++ b/ru/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_Date.rst b/ru/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/ru/api/Phalcon_Forms_Element_Date.rst +++ b/ru/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_Email.rst b/ru/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/ru/api/Phalcon_Forms_Element_Email.rst +++ b/ru/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_File.rst b/ru/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/ru/api/Phalcon_Forms_Element_File.rst +++ b/ru/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_Hidden.rst b/ru/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/ru/api/Phalcon_Forms_Element_Hidden.rst +++ b/ru/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_Numeric.rst b/ru/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/ru/api/Phalcon_Forms_Element_Numeric.rst +++ b/ru/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_Password.rst b/ru/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/ru/api/Phalcon_Forms_Element_Password.rst +++ b/ru/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_Radio.rst b/ru/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/ru/api/Phalcon_Forms_Element_Radio.rst +++ b/ru/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_Select.rst b/ru/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/ru/api/Phalcon_Forms_Element_Select.rst +++ b/ru/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_Submit.rst b/ru/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/ru/api/Phalcon_Forms_Element_Submit.rst +++ b/ru/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_Text.rst b/ru/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/ru/api/Phalcon_Forms_Element_Text.rst +++ b/ru/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Element_TextArea.rst b/ru/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/ru/api/Phalcon_Forms_Element_TextArea.rst +++ b/ru/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/ru/api/Phalcon_Forms_Manager.rst b/ru/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/ru/api/Phalcon_Forms_Manager.rst +++ b/ru/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/ru/api/Phalcon_Http_Cookie.rst b/ru/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/ru/api/Phalcon_Http_Cookie.rst +++ b/ru/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/ru/api/Phalcon_Http_Request.rst b/ru/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/ru/api/Phalcon_Http_Request.rst +++ b/ru/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/ru/api/Phalcon_Http_Request_File.rst b/ru/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/ru/api/Phalcon_Http_Request_File.rst +++ b/ru/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/ru/api/Phalcon_Http_Response.rst b/ru/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/ru/api/Phalcon_Http_Response.rst +++ b/ru/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/ru/api/Phalcon_Http_Response_Cookies.rst b/ru/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/ru/api/Phalcon_Http_Response_Cookies.rst +++ b/ru/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/ru/api/Phalcon_Image_Adapter.rst b/ru/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/ru/api/Phalcon_Image_Adapter.rst +++ b/ru/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/ru/api/Phalcon_Image_Adapter_Gd.rst b/ru/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/ru/api/Phalcon_Image_Adapter_Gd.rst +++ b/ru/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/ru/api/Phalcon_Image_Adapter_Imagick.rst b/ru/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/ru/api/Phalcon_Image_Adapter_Imagick.rst +++ b/ru/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/ru/api/Phalcon_Loader.rst b/ru/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/ru/api/Phalcon_Loader.rst +++ b/ru/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/ru/api/Phalcon_Logger_Adapter.rst b/ru/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/ru/api/Phalcon_Logger_Adapter.rst +++ b/ru/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/ru/api/Phalcon_Logger_Adapter_File.rst b/ru/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/ru/api/Phalcon_Logger_Adapter_File.rst +++ b/ru/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/ru/api/Phalcon_Logger_Adapter_Firephp.rst b/ru/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/ru/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/ru/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/ru/api/Phalcon_Logger_Adapter_Stream.rst b/ru/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/ru/api/Phalcon_Logger_Adapter_Stream.rst +++ b/ru/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/ru/api/Phalcon_Logger_Adapter_Syslog.rst b/ru/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/ru/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/ru/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/ru/api/Phalcon_Mvc_Application.rst b/ru/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/ru/api/Phalcon_Mvc_Application.rst +++ b/ru/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/ru/api/Phalcon_Mvc_Collection.rst b/ru/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/ru/api/Phalcon_Mvc_Collection.rst +++ b/ru/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/ru/api/Phalcon_Mvc_Collection_Behavior.rst b/ru/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/ru/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/ru/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/ru/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/ru/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/ru/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/ru/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/ru/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/ru/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/ru/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/ru/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/ru/api/Phalcon_Mvc_Collection_Document.rst b/ru/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/ru/api/Phalcon_Mvc_Collection_Document.rst +++ b/ru/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/ru/api/Phalcon_Mvc_Collection_Manager.rst b/ru/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/ru/api/Phalcon_Mvc_Collection_Manager.rst +++ b/ru/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/ru/api/Phalcon_Mvc_Controller.rst b/ru/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/ru/api/Phalcon_Mvc_Controller.rst +++ b/ru/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/ru/api/Phalcon_Mvc_Dispatcher.rst b/ru/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/ru/api/Phalcon_Mvc_Dispatcher.rst +++ b/ru/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/ru/api/Phalcon_Mvc_Micro.rst b/ru/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/ru/api/Phalcon_Mvc_Micro.rst +++ b/ru/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/ru/api/Phalcon_Mvc_Model.rst b/ru/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/ru/api/Phalcon_Mvc_Model.rst +++ b/ru/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/ru/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/ru/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/ru/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/ru/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/ru/api/Phalcon_Mvc_Model_Criteria.rst b/ru/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/ru/api/Phalcon_Mvc_Model_Criteria.rst +++ b/ru/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/ru/api/Phalcon_Mvc_Model_Manager.rst b/ru/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/ru/api/Phalcon_Mvc_Model_Manager.rst +++ b/ru/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/ru/api/Phalcon_Mvc_Model_Message.rst b/ru/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/ru/api/Phalcon_Mvc_Model_Message.rst +++ b/ru/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/ru/api/Phalcon_Mvc_Model_MetaData.rst b/ru/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/ru/api/Phalcon_Mvc_Model_MetaData.rst +++ b/ru/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ru/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/ru/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/ru/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/ru/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ru/api/Phalcon_Mvc_Model_MetaData_Files.rst b/ru/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/ru/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/ru/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ru/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/ru/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/ru/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/ru/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/ru/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/ru/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/ru/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/ru/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/ru/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/ru/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/ru/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/ru/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ru/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/ru/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/ru/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/ru/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/ru/api/Phalcon_Mvc_Model_MetaData_Session.rst b/ru/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/ru/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/ru/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ru/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/ru/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/ru/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/ru/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/ru/api/Phalcon_Mvc_Model_Query.rst b/ru/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/ru/api/Phalcon_Mvc_Model_Query.rst +++ b/ru/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/ru/api/Phalcon_Mvc_Model_Query_Builder.rst b/ru/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/ru/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/ru/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/ru/api/Phalcon_Mvc_Model_Query_Lang.rst b/ru/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/ru/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/ru/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/ru/api/Phalcon_Mvc_Model_Relation.rst b/ru/api/Phalcon_Mvc_Model_Relation.rst index bbd49acbd3ac..7a0c5587b554 100644 --- a/ru/api/Phalcon_Mvc_Model_Relation.rst +++ b/ru/api/Phalcon_Mvc_Model_Relation.rst @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned diff --git a/ru/api/Phalcon_Mvc_Model_Resultset.rst b/ru/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/ru/api/Phalcon_Mvc_Model_Resultset.rst +++ b/ru/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/ru/api/Phalcon_Mvc_Model_Transaction.rst b/ru/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/ru/api/Phalcon_Mvc_Model_Transaction.rst +++ b/ru/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/ru/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/ru/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/ru/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/ru/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/ru/api/Phalcon_Mvc_Model_ValidationFailed.rst b/ru/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/ru/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/ru/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/ru/api/Phalcon_Mvc_Model_Validator.rst b/ru/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/ru/api/Phalcon_Mvc_Model_Validator_Email.rst b/ru/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ru/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/ru/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ru/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/ru/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ru/api/Phalcon_Mvc_Model_Validator_Ip.rst b/ru/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ru/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/ru/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ru/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/ru/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ru/api/Phalcon_Mvc_Model_Validator_Regex.rst b/ru/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/ru/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/ru/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ru/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/ru/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ru/api/Phalcon_Mvc_Model_Validator_Url.rst b/ru/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/ru/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/ru/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/ru/api/Phalcon_Mvc_Router.rst b/ru/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/ru/api/Phalcon_Mvc_Router.rst +++ b/ru/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/ru/api/Phalcon_Mvc_Router_Annotations.rst b/ru/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/ru/api/Phalcon_Mvc_Router_Annotations.rst +++ b/ru/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/ru/api/Phalcon_Mvc_Router_Group.rst b/ru/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/ru/api/Phalcon_Mvc_Router_Group.rst +++ b/ru/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/ru/api/Phalcon_Mvc_Router_Route.rst b/ru/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/ru/api/Phalcon_Mvc_Router_Route.rst +++ b/ru/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/ru/api/Phalcon_Mvc_Url.rst b/ru/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/ru/api/Phalcon_Mvc_Url.rst +++ b/ru/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/ru/api/Phalcon_Mvc_View.rst b/ru/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/ru/api/Phalcon_Mvc_View.rst +++ b/ru/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/ru/api/Phalcon_Mvc_View_Engine.rst b/ru/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/ru/api/Phalcon_Mvc_View_Engine.rst +++ b/ru/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/ru/api/Phalcon_Mvc_View_Engine_Php.rst b/ru/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/ru/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/ru/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/ru/api/Phalcon_Mvc_View_Engine_Volt.rst b/ru/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/ru/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/ru/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/ru/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/ru/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/ru/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/ru/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/ru/api/Phalcon_Mvc_View_Simple.rst b/ru/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/ru/api/Phalcon_Mvc_View_Simple.rst +++ b/ru/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/ru/api/Phalcon_Paginator_Adapter.rst b/ru/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/ru/api/Phalcon_Paginator_Adapter.rst +++ b/ru/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/ru/api/Phalcon_Paginator_Adapter_Model.rst b/ru/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/ru/api/Phalcon_Paginator_Adapter_Model.rst +++ b/ru/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/ru/api/Phalcon_Paginator_Adapter_NativeArray.rst b/ru/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/ru/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/ru/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/ru/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/ru/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/ru/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/ru/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/ru/api/Phalcon_Queue_Beanstalk.rst b/ru/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/ru/api/Phalcon_Queue_Beanstalk.rst +++ b/ru/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/ru/api/Phalcon_Queue_Beanstalk_Job.rst b/ru/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/ru/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/ru/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/ru/api/Phalcon_Registry.rst b/ru/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/ru/api/Phalcon_Registry.rst +++ b/ru/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/ru/api/Phalcon_Security.rst b/ru/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/ru/api/Phalcon_Security.rst +++ b/ru/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/ru/api/Phalcon_Security_Random.rst b/ru/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/ru/api/Phalcon_Security_Random.rst +++ b/ru/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/ru/api/Phalcon_Session_Adapter.rst b/ru/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/ru/api/Phalcon_Session_Adapter.rst +++ b/ru/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/ru/api/Phalcon_Session_Adapter_Files.rst b/ru/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/ru/api/Phalcon_Session_Adapter_Files.rst +++ b/ru/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/ru/api/Phalcon_Session_Adapter_Libmemcached.rst b/ru/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/ru/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/ru/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/ru/api/Phalcon_Session_Adapter_Memcache.rst b/ru/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/ru/api/Phalcon_Session_Adapter_Memcache.rst +++ b/ru/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/ru/api/Phalcon_Session_Adapter_Redis.rst b/ru/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/ru/api/Phalcon_Session_Adapter_Redis.rst +++ b/ru/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/ru/api/Phalcon_Session_Bag.rst b/ru/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/ru/api/Phalcon_Session_Bag.rst +++ b/ru/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/ru/api/Phalcon_Tag.rst b/ru/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/ru/api/Phalcon_Tag.rst +++ b/ru/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/ru/api/Phalcon_Translate_Adapter_Gettext.rst b/ru/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/ru/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/ru/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/ru/api/Phalcon_Validation.rst b/ru/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/ru/api/Phalcon_Validation.rst +++ b/ru/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/ru/api/Phalcon_Validation_CombinedFieldsValidator.rst b/ru/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/ru/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/ru/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Message.rst b/ru/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/ru/api/Phalcon_Validation_Message.rst +++ b/ru/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/ru/api/Phalcon_Validation_Message_Group.rst b/ru/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/ru/api/Phalcon_Validation_Message_Group.rst +++ b/ru/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/ru/api/Phalcon_Validation_Validator.rst b/ru/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/ru/api/Phalcon_Validation_Validator.rst +++ b/ru/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Alnum.rst b/ru/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/ru/api/Phalcon_Validation_Validator_Alnum.rst +++ b/ru/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Alpha.rst b/ru/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/ru/api/Phalcon_Validation_Validator_Alpha.rst +++ b/ru/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Between.rst b/ru/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/ru/api/Phalcon_Validation_Validator_Between.rst +++ b/ru/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Confirmation.rst b/ru/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/ru/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/ru/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_CreditCard.rst b/ru/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/ru/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/ru/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Date.rst b/ru/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/ru/api/Phalcon_Validation_Validator_Date.rst +++ b/ru/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Digit.rst b/ru/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/ru/api/Phalcon_Validation_Validator_Digit.rst +++ b/ru/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Email.rst b/ru/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/ru/api/Phalcon_Validation_Validator_Email.rst +++ b/ru/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_ExclusionIn.rst b/ru/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/ru/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/ru/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_File.rst b/ru/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/ru/api/Phalcon_Validation_Validator_File.rst +++ b/ru/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Identical.rst b/ru/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/ru/api/Phalcon_Validation_Validator_Identical.rst +++ b/ru/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_InclusionIn.rst b/ru/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/ru/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/ru/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Numericality.rst b/ru/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/ru/api/Phalcon_Validation_Validator_Numericality.rst +++ b/ru/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_PresenceOf.rst b/ru/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/ru/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/ru/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Regex.rst b/ru/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/ru/api/Phalcon_Validation_Validator_Regex.rst +++ b/ru/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_StringLength.rst b/ru/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/ru/api/Phalcon_Validation_Validator_StringLength.rst +++ b/ru/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Uniqueness.rst b/ru/api/Phalcon_Validation_Validator_Uniqueness.rst index af0bde58d45d..8af5174ddfba 100644 --- a/ru/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/ru/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,59 +10,84 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; - Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); - In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); + $validator->add( + "username", + new UniquenessValidator() + ); - Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); - It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); @@ -106,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Validation_Validator_Url.rst b/ru/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/ru/api/Phalcon_Validation_Validator_Url.rst +++ b/ru/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/ru/api/Phalcon_Version.rst b/ru/api/Phalcon_Version.rst index 4322c6cb17bb..77d94d7b0e5a 100644 --- a/ru/api/Phalcon_Version.rst +++ b/ru/api/Phalcon_Version.rst @@ -27,51 +27,61 @@ 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. +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. final protected static **_getSpecial** (*mixed* $special) -Translates a number to a special release If Special release = 1 this function will return ALPHA +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -Returns the active version (string) +Returns the active version (string) .. code-block:: php Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/uk/api/Phalcon_Annotations_Adapter_Apc.rst b/uk/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/uk/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/uk/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/uk/api/Phalcon_Annotations_Adapter_Files.rst b/uk/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/uk/api/Phalcon_Annotations_Adapter_Files.rst +++ b/uk/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/uk/api/Phalcon_Annotations_Adapter_Memory.rst b/uk/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/uk/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/uk/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/uk/api/Phalcon_Annotations_Adapter_Xcache.rst b/uk/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/uk/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/uk/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/uk/api/Phalcon_Annotations_Reflection.rst b/uk/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/uk/api/Phalcon_Annotations_Reflection.rst +++ b/uk/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/uk/api/Phalcon_Application.rst b/uk/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/uk/api/Phalcon_Application.rst +++ b/uk/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/uk/api/Phalcon_Assets_Filters_Cssmin.rst b/uk/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/uk/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/uk/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/uk/api/Phalcon_Assets_Filters_Jsmin.rst b/uk/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/uk/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/uk/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/uk/api/Phalcon_Assets_Inline.rst b/uk/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/uk/api/Phalcon_Assets_Inline.rst +++ b/uk/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/uk/api/Phalcon_Assets_Resource.rst b/uk/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/uk/api/Phalcon_Assets_Resource.rst +++ b/uk/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/uk/api/Phalcon_Assets_Resource_Js.rst b/uk/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/uk/api/Phalcon_Assets_Resource_Js.rst +++ b/uk/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/uk/api/Phalcon_Cache_Backend.rst b/uk/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/uk/api/Phalcon_Cache_Backend.rst +++ b/uk/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/uk/api/Phalcon_Cache_Backend_Apc.rst b/uk/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/uk/api/Phalcon_Cache_Backend_Apc.rst +++ b/uk/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/uk/api/Phalcon_Cache_Backend_File.rst b/uk/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/uk/api/Phalcon_Cache_Backend_File.rst +++ b/uk/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/uk/api/Phalcon_Cache_Backend_Libmemcached.rst b/uk/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/uk/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/uk/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/uk/api/Phalcon_Cache_Backend_Memcache.rst b/uk/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/uk/api/Phalcon_Cache_Backend_Memcache.rst +++ b/uk/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/uk/api/Phalcon_Cache_Backend_Memory.rst b/uk/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/uk/api/Phalcon_Cache_Backend_Memory.rst +++ b/uk/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/uk/api/Phalcon_Cache_Backend_Mongo.rst b/uk/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/uk/api/Phalcon_Cache_Backend_Mongo.rst +++ b/uk/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/uk/api/Phalcon_Cache_Backend_Redis.rst b/uk/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/uk/api/Phalcon_Cache_Backend_Redis.rst +++ b/uk/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/uk/api/Phalcon_Cache_Backend_Xcache.rst b/uk/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/uk/api/Phalcon_Cache_Backend_Xcache.rst +++ b/uk/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/uk/api/Phalcon_Cache_Frontend_Base64.rst b/uk/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/uk/api/Phalcon_Cache_Frontend_Base64.rst +++ b/uk/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/uk/api/Phalcon_Cache_Frontend_Data.rst b/uk/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/uk/api/Phalcon_Cache_Frontend_Data.rst +++ b/uk/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/uk/api/Phalcon_Cache_Frontend_Igbinary.rst b/uk/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/uk/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/uk/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/uk/api/Phalcon_Cache_Frontend_Json.rst b/uk/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/uk/api/Phalcon_Cache_Frontend_Json.rst +++ b/uk/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/uk/api/Phalcon_Cache_Frontend_Msgpack.rst b/uk/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/uk/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/uk/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/uk/api/Phalcon_Cache_Frontend_None.rst b/uk/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/uk/api/Phalcon_Cache_Frontend_None.rst +++ b/uk/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/uk/api/Phalcon_Cache_Frontend_Output.rst b/uk/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/uk/api/Phalcon_Cache_Frontend_Output.rst +++ b/uk/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/uk/api/Phalcon_Cache_Multiple.rst b/uk/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/uk/api/Phalcon_Cache_Multiple.rst +++ b/uk/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/uk/api/Phalcon_Cli_Console.rst b/uk/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/uk/api/Phalcon_Cli_Console.rst +++ b/uk/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/uk/api/Phalcon_Cli_Dispatcher.rst b/uk/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/uk/api/Phalcon_Cli_Dispatcher.rst +++ b/uk/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/uk/api/Phalcon_Cli_Router.rst b/uk/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/uk/api/Phalcon_Cli_Router.rst +++ b/uk/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/uk/api/Phalcon_Cli_Router_Route.rst b/uk/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/uk/api/Phalcon_Cli_Router_Route.rst +++ b/uk/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/uk/api/Phalcon_Cli_Task.rst b/uk/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/uk/api/Phalcon_Cli_Task.rst +++ b/uk/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/uk/api/Phalcon_Config.rst b/uk/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/uk/api/Phalcon_Config.rst +++ b/uk/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/uk/api/Phalcon_Config_Adapter_Ini.rst b/uk/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/uk/api/Phalcon_Config_Adapter_Ini.rst +++ b/uk/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/uk/api/Phalcon_Config_Adapter_Json.rst b/uk/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/uk/api/Phalcon_Config_Adapter_Json.rst +++ b/uk/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/uk/api/Phalcon_Config_Adapter_Php.rst b/uk/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/uk/api/Phalcon_Config_Adapter_Php.rst +++ b/uk/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/uk/api/Phalcon_Config_Adapter_Yaml.rst b/uk/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/uk/api/Phalcon_Config_Adapter_Yaml.rst +++ b/uk/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/uk/api/Phalcon_Crypt.rst b/uk/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/uk/api/Phalcon_Crypt.rst +++ b/uk/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/uk/api/Phalcon_Db.rst b/uk/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/uk/api/Phalcon_Db.rst +++ b/uk/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/uk/api/Phalcon_Db_Adapter.rst b/uk/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/uk/api/Phalcon_Db_Adapter.rst +++ b/uk/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/uk/api/Phalcon_Db_Adapter_Pdo.rst b/uk/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/uk/api/Phalcon_Db_Adapter_Pdo.rst +++ b/uk/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/uk/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/uk/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/uk/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/uk/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/uk/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/uk/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/uk/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/uk/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/uk/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/uk/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/uk/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/uk/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/uk/api/Phalcon_Db_Column.rst b/uk/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/uk/api/Phalcon_Db_Column.rst +++ b/uk/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/uk/api/Phalcon_Db_Dialect.rst b/uk/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/uk/api/Phalcon_Db_Dialect.rst +++ b/uk/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/uk/api/Phalcon_Db_Dialect_Mysql.rst b/uk/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/uk/api/Phalcon_Db_Dialect_Mysql.rst +++ b/uk/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/uk/api/Phalcon_Db_Dialect_Postgresql.rst b/uk/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/uk/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/uk/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/uk/api/Phalcon_Db_Dialect_Sqlite.rst b/uk/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/uk/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/uk/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/uk/api/Phalcon_Db_Index.rst b/uk/api/Phalcon_Db_Index.rst index 227b766ccbe8..415a456a64bd 100644 --- a/uk/api/Phalcon_Db_Index.rst +++ b/uk/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods diff --git a/uk/api/Phalcon_Db_Profiler.rst b/uk/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/uk/api/Phalcon_Db_Profiler.rst +++ b/uk/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/uk/api/Phalcon_Db_RawValue.rst b/uk/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/uk/api/Phalcon_Db_RawValue.rst +++ b/uk/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/uk/api/Phalcon_Db_Reference.rst b/uk/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/uk/api/Phalcon_Db_Reference.rst +++ b/uk/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/uk/api/Phalcon_Db_Result_Pdo.rst b/uk/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/uk/api/Phalcon_Db_Result_Pdo.rst +++ b/uk/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/uk/api/Phalcon_Debug.rst b/uk/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/uk/api/Phalcon_Debug.rst +++ b/uk/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/uk/api/Phalcon_Debug_Dump.rst b/uk/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/uk/api/Phalcon_Debug_Dump.rst +++ b/uk/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/uk/api/Phalcon_Di.rst b/uk/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/uk/api/Phalcon_Di.rst +++ b/uk/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/uk/api/Phalcon_Di_FactoryDefault.rst b/uk/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/uk/api/Phalcon_Di_FactoryDefault.rst +++ b/uk/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/uk/api/Phalcon_Di_FactoryDefault_Cli.rst b/uk/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/uk/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/uk/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/uk/api/Phalcon_Di_Injectable.rst b/uk/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/uk/api/Phalcon_Di_Injectable.rst +++ b/uk/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/uk/api/Phalcon_Di_Service.rst b/uk/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/uk/api/Phalcon_Di_Service.rst +++ b/uk/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/uk/api/Phalcon_Dispatcher.rst b/uk/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/uk/api/Phalcon_Dispatcher.rst +++ b/uk/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/uk/api/Phalcon_Escaper.rst b/uk/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/uk/api/Phalcon_Escaper.rst +++ b/uk/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/uk/api/Phalcon_Events_Event.rst b/uk/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/uk/api/Phalcon_Events_Event.rst +++ b/uk/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/uk/api/Phalcon_Events_Manager.rst b/uk/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/uk/api/Phalcon_Events_Manager.rst +++ b/uk/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/uk/api/Phalcon_Filter.rst b/uk/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/uk/api/Phalcon_Filter.rst +++ b/uk/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/uk/api/Phalcon_Flash.rst b/uk/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/uk/api/Phalcon_Flash.rst +++ b/uk/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/uk/api/Phalcon_Flash_Direct.rst b/uk/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/uk/api/Phalcon_Flash_Direct.rst +++ b/uk/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/uk/api/Phalcon_Flash_Session.rst b/uk/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/uk/api/Phalcon_Flash_Session.rst +++ b/uk/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/uk/api/Phalcon_Forms_Element.rst b/uk/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/uk/api/Phalcon_Forms_Element.rst +++ b/uk/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_Check.rst b/uk/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/uk/api/Phalcon_Forms_Element_Check.rst +++ b/uk/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_Date.rst b/uk/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/uk/api/Phalcon_Forms_Element_Date.rst +++ b/uk/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_Email.rst b/uk/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/uk/api/Phalcon_Forms_Element_Email.rst +++ b/uk/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_File.rst b/uk/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/uk/api/Phalcon_Forms_Element_File.rst +++ b/uk/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_Hidden.rst b/uk/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/uk/api/Phalcon_Forms_Element_Hidden.rst +++ b/uk/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_Numeric.rst b/uk/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/uk/api/Phalcon_Forms_Element_Numeric.rst +++ b/uk/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_Password.rst b/uk/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/uk/api/Phalcon_Forms_Element_Password.rst +++ b/uk/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_Radio.rst b/uk/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/uk/api/Phalcon_Forms_Element_Radio.rst +++ b/uk/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_Select.rst b/uk/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/uk/api/Phalcon_Forms_Element_Select.rst +++ b/uk/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_Submit.rst b/uk/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/uk/api/Phalcon_Forms_Element_Submit.rst +++ b/uk/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_Text.rst b/uk/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/uk/api/Phalcon_Forms_Element_Text.rst +++ b/uk/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Element_TextArea.rst b/uk/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/uk/api/Phalcon_Forms_Element_TextArea.rst +++ b/uk/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/uk/api/Phalcon_Forms_Manager.rst b/uk/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/uk/api/Phalcon_Forms_Manager.rst +++ b/uk/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/uk/api/Phalcon_Http_Cookie.rst b/uk/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/uk/api/Phalcon_Http_Cookie.rst +++ b/uk/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/uk/api/Phalcon_Http_Request.rst b/uk/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/uk/api/Phalcon_Http_Request.rst +++ b/uk/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/uk/api/Phalcon_Http_Request_File.rst b/uk/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/uk/api/Phalcon_Http_Request_File.rst +++ b/uk/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/uk/api/Phalcon_Http_Response.rst b/uk/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/uk/api/Phalcon_Http_Response.rst +++ b/uk/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/uk/api/Phalcon_Http_Response_Cookies.rst b/uk/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/uk/api/Phalcon_Http_Response_Cookies.rst +++ b/uk/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/uk/api/Phalcon_Image_Adapter.rst b/uk/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/uk/api/Phalcon_Image_Adapter.rst +++ b/uk/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/uk/api/Phalcon_Image_Adapter_Gd.rst b/uk/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/uk/api/Phalcon_Image_Adapter_Gd.rst +++ b/uk/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/uk/api/Phalcon_Image_Adapter_Imagick.rst b/uk/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/uk/api/Phalcon_Image_Adapter_Imagick.rst +++ b/uk/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/uk/api/Phalcon_Loader.rst b/uk/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/uk/api/Phalcon_Loader.rst +++ b/uk/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/uk/api/Phalcon_Logger_Adapter.rst b/uk/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/uk/api/Phalcon_Logger_Adapter.rst +++ b/uk/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/uk/api/Phalcon_Logger_Adapter_File.rst b/uk/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/uk/api/Phalcon_Logger_Adapter_File.rst +++ b/uk/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/uk/api/Phalcon_Logger_Adapter_Firephp.rst b/uk/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/uk/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/uk/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/uk/api/Phalcon_Logger_Adapter_Stream.rst b/uk/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/uk/api/Phalcon_Logger_Adapter_Stream.rst +++ b/uk/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/uk/api/Phalcon_Logger_Adapter_Syslog.rst b/uk/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/uk/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/uk/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/uk/api/Phalcon_Mvc_Application.rst b/uk/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/uk/api/Phalcon_Mvc_Application.rst +++ b/uk/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/uk/api/Phalcon_Mvc_Collection.rst b/uk/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/uk/api/Phalcon_Mvc_Collection.rst +++ b/uk/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/uk/api/Phalcon_Mvc_Collection_Behavior.rst b/uk/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/uk/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/uk/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/uk/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/uk/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/uk/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/uk/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/uk/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/uk/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/uk/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/uk/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/uk/api/Phalcon_Mvc_Collection_Document.rst b/uk/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/uk/api/Phalcon_Mvc_Collection_Document.rst +++ b/uk/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/uk/api/Phalcon_Mvc_Collection_Manager.rst b/uk/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/uk/api/Phalcon_Mvc_Collection_Manager.rst +++ b/uk/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/uk/api/Phalcon_Mvc_Controller.rst b/uk/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/uk/api/Phalcon_Mvc_Controller.rst +++ b/uk/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/uk/api/Phalcon_Mvc_Dispatcher.rst b/uk/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/uk/api/Phalcon_Mvc_Dispatcher.rst +++ b/uk/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/uk/api/Phalcon_Mvc_Micro.rst b/uk/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/uk/api/Phalcon_Mvc_Micro.rst +++ b/uk/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/uk/api/Phalcon_Mvc_Model.rst b/uk/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/uk/api/Phalcon_Mvc_Model.rst +++ b/uk/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/uk/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/uk/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/uk/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/uk/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/uk/api/Phalcon_Mvc_Model_Criteria.rst b/uk/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/uk/api/Phalcon_Mvc_Model_Criteria.rst +++ b/uk/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/uk/api/Phalcon_Mvc_Model_Manager.rst b/uk/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/uk/api/Phalcon_Mvc_Model_Manager.rst +++ b/uk/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/uk/api/Phalcon_Mvc_Model_Message.rst b/uk/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/uk/api/Phalcon_Mvc_Model_Message.rst +++ b/uk/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/uk/api/Phalcon_Mvc_Model_MetaData.rst b/uk/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/uk/api/Phalcon_Mvc_Model_MetaData.rst +++ b/uk/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/uk/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/uk/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/uk/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/uk/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/uk/api/Phalcon_Mvc_Model_MetaData_Files.rst b/uk/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/uk/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/uk/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/uk/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/uk/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/uk/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/uk/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/uk/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/uk/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/uk/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/uk/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/uk/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/uk/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/uk/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/uk/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/uk/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/uk/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/uk/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/uk/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/uk/api/Phalcon_Mvc_Model_MetaData_Session.rst b/uk/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/uk/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/uk/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/uk/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/uk/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/uk/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/uk/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/uk/api/Phalcon_Mvc_Model_Query.rst b/uk/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/uk/api/Phalcon_Mvc_Model_Query.rst +++ b/uk/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/uk/api/Phalcon_Mvc_Model_Query_Builder.rst b/uk/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/uk/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/uk/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/uk/api/Phalcon_Mvc_Model_Query_Lang.rst b/uk/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/uk/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/uk/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/uk/api/Phalcon_Mvc_Model_Relation.rst b/uk/api/Phalcon_Mvc_Model_Relation.rst index bbd49acbd3ac..7a0c5587b554 100644 --- a/uk/api/Phalcon_Mvc_Model_Relation.rst +++ b/uk/api/Phalcon_Mvc_Model_Relation.rst @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned diff --git a/uk/api/Phalcon_Mvc_Model_Resultset.rst b/uk/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/uk/api/Phalcon_Mvc_Model_Resultset.rst +++ b/uk/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/uk/api/Phalcon_Mvc_Model_Transaction.rst b/uk/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/uk/api/Phalcon_Mvc_Model_Transaction.rst +++ b/uk/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/uk/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/uk/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/uk/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/uk/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/uk/api/Phalcon_Mvc_Model_ValidationFailed.rst b/uk/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/uk/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/uk/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/uk/api/Phalcon_Mvc_Model_Validator.rst b/uk/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/uk/api/Phalcon_Mvc_Model_Validator_Email.rst b/uk/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/uk/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/uk/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/uk/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/uk/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/uk/api/Phalcon_Mvc_Model_Validator_Ip.rst b/uk/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/uk/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/uk/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/uk/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/uk/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/uk/api/Phalcon_Mvc_Model_Validator_Regex.rst b/uk/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/uk/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/uk/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/uk/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/uk/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/uk/api/Phalcon_Mvc_Model_Validator_Url.rst b/uk/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/uk/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/uk/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/uk/api/Phalcon_Mvc_Router.rst b/uk/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/uk/api/Phalcon_Mvc_Router.rst +++ b/uk/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/uk/api/Phalcon_Mvc_Router_Annotations.rst b/uk/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/uk/api/Phalcon_Mvc_Router_Annotations.rst +++ b/uk/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/uk/api/Phalcon_Mvc_Router_Group.rst b/uk/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/uk/api/Phalcon_Mvc_Router_Group.rst +++ b/uk/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/uk/api/Phalcon_Mvc_Router_Route.rst b/uk/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/uk/api/Phalcon_Mvc_Router_Route.rst +++ b/uk/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/uk/api/Phalcon_Mvc_Url.rst b/uk/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/uk/api/Phalcon_Mvc_Url.rst +++ b/uk/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/uk/api/Phalcon_Mvc_View.rst b/uk/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/uk/api/Phalcon_Mvc_View.rst +++ b/uk/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/uk/api/Phalcon_Mvc_View_Engine.rst b/uk/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/uk/api/Phalcon_Mvc_View_Engine.rst +++ b/uk/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/uk/api/Phalcon_Mvc_View_Engine_Php.rst b/uk/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/uk/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/uk/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/uk/api/Phalcon_Mvc_View_Engine_Volt.rst b/uk/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/uk/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/uk/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/uk/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/uk/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/uk/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/uk/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/uk/api/Phalcon_Mvc_View_Simple.rst b/uk/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/uk/api/Phalcon_Mvc_View_Simple.rst +++ b/uk/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/uk/api/Phalcon_Paginator_Adapter.rst b/uk/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/uk/api/Phalcon_Paginator_Adapter.rst +++ b/uk/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/uk/api/Phalcon_Paginator_Adapter_Model.rst b/uk/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/uk/api/Phalcon_Paginator_Adapter_Model.rst +++ b/uk/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/uk/api/Phalcon_Paginator_Adapter_NativeArray.rst b/uk/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/uk/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/uk/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/uk/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/uk/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/uk/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/uk/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/uk/api/Phalcon_Queue_Beanstalk.rst b/uk/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/uk/api/Phalcon_Queue_Beanstalk.rst +++ b/uk/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/uk/api/Phalcon_Queue_Beanstalk_Job.rst b/uk/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/uk/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/uk/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/uk/api/Phalcon_Registry.rst b/uk/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/uk/api/Phalcon_Registry.rst +++ b/uk/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/uk/api/Phalcon_Security.rst b/uk/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/uk/api/Phalcon_Security.rst +++ b/uk/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/uk/api/Phalcon_Security_Random.rst b/uk/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/uk/api/Phalcon_Security_Random.rst +++ b/uk/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/uk/api/Phalcon_Session_Adapter.rst b/uk/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/uk/api/Phalcon_Session_Adapter.rst +++ b/uk/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/uk/api/Phalcon_Session_Adapter_Files.rst b/uk/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/uk/api/Phalcon_Session_Adapter_Files.rst +++ b/uk/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/uk/api/Phalcon_Session_Adapter_Libmemcached.rst b/uk/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/uk/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/uk/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/uk/api/Phalcon_Session_Adapter_Memcache.rst b/uk/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/uk/api/Phalcon_Session_Adapter_Memcache.rst +++ b/uk/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/uk/api/Phalcon_Session_Adapter_Redis.rst b/uk/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/uk/api/Phalcon_Session_Adapter_Redis.rst +++ b/uk/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/uk/api/Phalcon_Session_Bag.rst b/uk/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/uk/api/Phalcon_Session_Bag.rst +++ b/uk/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/uk/api/Phalcon_Tag.rst b/uk/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/uk/api/Phalcon_Tag.rst +++ b/uk/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/uk/api/Phalcon_Translate_Adapter_Gettext.rst b/uk/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/uk/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/uk/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/uk/api/Phalcon_Validation.rst b/uk/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/uk/api/Phalcon_Validation.rst +++ b/uk/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/uk/api/Phalcon_Validation_CombinedFieldsValidator.rst b/uk/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/uk/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/uk/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Message.rst b/uk/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/uk/api/Phalcon_Validation_Message.rst +++ b/uk/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/uk/api/Phalcon_Validation_Message_Group.rst b/uk/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/uk/api/Phalcon_Validation_Message_Group.rst +++ b/uk/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/uk/api/Phalcon_Validation_Validator.rst b/uk/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/uk/api/Phalcon_Validation_Validator.rst +++ b/uk/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Alnum.rst b/uk/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/uk/api/Phalcon_Validation_Validator_Alnum.rst +++ b/uk/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Alpha.rst b/uk/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/uk/api/Phalcon_Validation_Validator_Alpha.rst +++ b/uk/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Between.rst b/uk/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/uk/api/Phalcon_Validation_Validator_Between.rst +++ b/uk/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Confirmation.rst b/uk/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/uk/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/uk/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_CreditCard.rst b/uk/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/uk/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/uk/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Date.rst b/uk/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/uk/api/Phalcon_Validation_Validator_Date.rst +++ b/uk/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Digit.rst b/uk/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/uk/api/Phalcon_Validation_Validator_Digit.rst +++ b/uk/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Email.rst b/uk/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/uk/api/Phalcon_Validation_Validator_Email.rst +++ b/uk/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_ExclusionIn.rst b/uk/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/uk/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/uk/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_File.rst b/uk/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/uk/api/Phalcon_Validation_Validator_File.rst +++ b/uk/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Identical.rst b/uk/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/uk/api/Phalcon_Validation_Validator_Identical.rst +++ b/uk/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_InclusionIn.rst b/uk/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/uk/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/uk/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Numericality.rst b/uk/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/uk/api/Phalcon_Validation_Validator_Numericality.rst +++ b/uk/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_PresenceOf.rst b/uk/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/uk/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/uk/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Regex.rst b/uk/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/uk/api/Phalcon_Validation_Validator_Regex.rst +++ b/uk/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_StringLength.rst b/uk/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/uk/api/Phalcon_Validation_Validator_StringLength.rst +++ b/uk/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Uniqueness.rst b/uk/api/Phalcon_Validation_Validator_Uniqueness.rst index af0bde58d45d..8af5174ddfba 100644 --- a/uk/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/uk/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,59 +10,84 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; - Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); - In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); + $validator->add( + "username", + new UniquenessValidator() + ); - Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); - It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); @@ -106,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Validation_Validator_Url.rst b/uk/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/uk/api/Phalcon_Validation_Validator_Url.rst +++ b/uk/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/uk/api/Phalcon_Version.rst b/uk/api/Phalcon_Version.rst index 4322c6cb17bb..77d94d7b0e5a 100644 --- a/uk/api/Phalcon_Version.rst +++ b/uk/api/Phalcon_Version.rst @@ -27,51 +27,61 @@ 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. +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. final protected static **_getSpecial** (*mixed* $special) -Translates a number to a special release If Special release = 1 this function will return ALPHA +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -Returns the active version (string) +Returns the active version (string) .. code-block:: php Source on GitHub` -Manages ACL lists in memory +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') + + $acl->setDefaultAction( + \Phalcon\Acl::DENY ); + + // Register roles + $roles = [ + "users" => new \Phalcon\Acl\Role("Users"), + "guests" => new \Phalcon\Acl\Role("Guests"), + ]; foreach ($roles as $role) { - $acl->addRole($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 + $privateResources = [ + "companies" => ["index", "search", "new", "edit", "save", "create", "delete"], + "products" => ["index", "search", "new", "edit", "save", "create", "delete"], + "invoices" => ["index", "profile"], + ]; + + foreach ($privateResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Public 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); + + // Public area resources + $publicResources = [ + "index" => ["index"], + "about" => ["index"], + "session" => ["index", "register", "start", "end"], + "contact" => ["index", "send"], + ]; + + foreach ($publicResources as $resourceName => $actions) { + $acl->addResource( + new \Phalcon\Acl\Resource($resourceName), + $actions + ); } - - //Grant access to public areas to both users and guests + + // Grant access to public areas to both users and guests foreach ($roles as $role){ - foreach ($publicResources as $resource => $actions) { - $acl->allow($role->getName(), $resource, '*'); - } + foreach ($publicResources as $resource => $actions) { + $acl->allow($role->getName(), $resource, "*"); + } } - - //Grant access to private area to role Users + + // Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { - foreach ($actions as $action) { - $acl->allow('Users', $resource, $action); - } + foreach ($actions as $action) { + $acl->allow("Users", $resource, $action); + } } @@ -77,14 +87,19 @@ Phalcon\\Acl\\Adapter\\Memory constructor public **addRole** (*RoleInterface* | *string* $role, [*array* | *string* $accessInherits]) -Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example: +Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role +Example: .. code-block:: php addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); - $acl->addRole('administrator', 'consultant'); + $acl->addRole( + new Phalcon\Acl\Role("administrator"), + "consultant" + ); + + $acl->addRole("administrator", "consultant"); @@ -109,19 +124,39 @@ Check whether resource exist in the resources list public **addResource** (:doc:`Phalcon\\Acl\\Resource ` | *string* $resourceValue, *array* | *string* $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: +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')); + // Add a resource to the the list allowing access to an action + $acl->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"), + [ + "create", + "search", + ] + ); + + $acl->addResource( + "customers", + [ + "create", + "search", + ] + ); @@ -146,76 +181,83 @@ Checks if a role has access to a resource public **allow** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Allow access to a role on a resource You can use '*' as wildcard Example: +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'); + //Allow access to guests to search on customers + $acl->allow("guests", "customers", "search"); + + //Allow access to guests to search or create on customers + $acl->allow("guests", "customers", ["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 **deny** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*mixed* $func]) -Deny access to a role on a resource You can use '*' as wildcard Example: +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'); + //Deny access to guests to search on customers + $acl->deny("guests", "customers", "search"); + + //Deny access to guests to search or create on customers + $acl->deny("guests", "customers", ["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 **isAllowed** (*mixed* $roleName, *mixed* $resourceName, *mixed* $access, [*array* $parameters]) -Check whether a role is allowed to access an action from a resource +public **isAllowed** (*RoleInterface* | *RoleAware* | *string* $roleName, *ResourceInterface* | *ResourceAware* | *string* $resourceName, *mixed* $access, [*array* $parameters]) + +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'); + //Does andres have access to the customers resource to create? + $acl->isAllowed("andres", "Products", "create"); + + //Do guests have access to any resource to edit? + $acl->isAllowed("guests", "*", "edit"); public **setNoArgumentsDefaultAction** (*mixed* $defaultAccess) -Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) +for no arguments provided in isAllowed action if there exists func for +accessKey public **getNoArgumentsDefaultAction** () -Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey +Returns the default ACL access level for no arguments provided in +isAllowed action if there exists func for accessKey diff --git a/zh/api/Phalcon_Annotations_Adapter_Apc.rst b/zh/api/Phalcon_Annotations_Adapter_Apc.rst index 9c8c0a2c39a1..27291733b1f7 100644 --- a/zh/api/Phalcon_Annotations_Adapter_Apc.rst +++ b/zh/api/Phalcon_Annotations_Adapter_Apc.rst @@ -10,13 +10,15 @@ Class **Phalcon\\Annotations\\Adapter\\Apc** :raw-html:`Source on GitHub` -Stores the parsed annotations in APC. This adapter is suitable for production +Stores the parsed annotations in APC. This adapter is suitable for production .. code-block:: php ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from APC diff --git a/zh/api/Phalcon_Annotations_Adapter_Files.rst b/zh/api/Phalcon_Annotations_Adapter_Files.rst index c6adf750bdae..2701ffaefd0a 100644 --- a/zh/api/Phalcon_Annotations_Adapter_Files.rst +++ b/zh/api/Phalcon_Annotations_Adapter_Files.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Annotations\\Adapter\\Files** :raw-html:`Source on GitHub` -Stores the parsed annotations in files. This adapter is suitable for production +Stores the parsed annotations in files. This adapter is suitable for production .. code-block:: php 'app/cache/annotations/']); + use Phalcon\Annotations\Adapter\Files; + + $annotations = new Files( + [ + "annotationsDir" => "app/cache/annotations/", + ] + ); diff --git a/zh/api/Phalcon_Annotations_Adapter_Memory.rst b/zh/api/Phalcon_Annotations_Adapter_Memory.rst index aa087bbd922b..ca1a318a21d2 100644 --- a/zh/api/Phalcon_Annotations_Adapter_Memory.rst +++ b/zh/api/Phalcon_Annotations_Adapter_Memory.rst @@ -16,7 +16,7 @@ Stores the parsed annotations in memory. This adapter is the suitable developmen Methods ------- -public :doc:`Phalcon\\Annotations\\Reflection ` **read** (*string* $key) +public **read** (*mixed* $key) Reads parsed annotations from memory diff --git a/zh/api/Phalcon_Annotations_Adapter_Xcache.rst b/zh/api/Phalcon_Annotations_Adapter_Xcache.rst index 64b9277cc09f..58c5fceb5410 100644 --- a/zh/api/Phalcon_Annotations_Adapter_Xcache.rst +++ b/zh/api/Phalcon_Annotations_Adapter_Xcache.rst @@ -10,13 +10,13 @@ Class **Phalcon\\Annotations\\Adapter\\Xcache** :raw-html:`Source on GitHub` -Stores the parsed annotations to XCache. This adapter is suitable for production +Stores the parsed annotations to XCache. This adapter is suitable for production .. code-block:: php Source on GitHub` -Represents a collection of annotations. This class allows to traverse a group of annotations easily +Represents a collection of annotations. This class allows to traverse a group of annotations easily .. code-block:: php getName(), PHP_EOL; - } - - //Check if the annotations has a specific - var_dump($classAnnotations->has('Cacheable')); - - //Get an specific annotation in the collection - $annotation = $classAnnotations->get('Cacheable'); + //Traverse annotations + foreach ($classAnnotations as $annotation) { + echo "Name=", $annotation->getName(), PHP_EOL; + } + + //Check if the annotations has a specific + var_dump($classAnnotations->has("Cacheable")); + + //Get an specific annotation in the collection + $annotation = $classAnnotations->get("Cacheable"); diff --git a/zh/api/Phalcon_Annotations_Reflection.rst b/zh/api/Phalcon_Annotations_Reflection.rst index 03dbf90e640e..f32fefd40212 100644 --- a/zh/api/Phalcon_Annotations_Reflection.rst +++ b/zh/api/Phalcon_Annotations_Reflection.rst @@ -6,24 +6,24 @@ Class **Phalcon\\Annotations\\Reflection** :raw-html:`Source on GitHub` -Allows to manipulate the annotations reflection in an OO manner +Allows to manipulate the annotations reflection in an OO manner .. code-block:: php parse('MyComponent'); - - // Create the reflection - $reflection = new Reflection($parsing); - - // Get the annotations in the class docblock - $classAnnotations = reflection->getClassAnnotations(); + use Phalcon\Annotations\Reader; + use Phalcon\Annotations\Reflection; + + // Parse the annotations in a class + $reader = new Reader(); + $parsing = $reader->parse("MyComponent"); + + // Create the reflection + $reflection = new Reflection($parsing); + + // Get the annotations in the class docblock + $classAnnotations = $reflection->getClassAnnotations(); diff --git a/zh/api/Phalcon_Application.rst b/zh/api/Phalcon_Application.rst index 393a863acf57..958c35e5da07 100644 --- a/zh/api/Phalcon_Application.rst +++ b/zh/api/Phalcon_Application.rst @@ -36,24 +36,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/zh/api/Phalcon_Assets_Filters_Cssmin.rst b/zh/api/Phalcon_Assets_Filters_Cssmin.rst index b4dea9b86d3e..b75d40404f45 100644 --- a/zh/api/Phalcon_Assets_Filters_Cssmin.rst +++ b/zh/api/Phalcon_Assets_Filters_Cssmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Cssmin** :raw-html:`Source on GitHub` -Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property +Minify the css - removes comments +removes newlines and line feeds keeping +removes last semicolon from last property Methods diff --git a/zh/api/Phalcon_Assets_Filters_Jsmin.rst b/zh/api/Phalcon_Assets_Filters_Jsmin.rst index 6f7bf658d130..2faeb8cbac8e 100644 --- a/zh/api/Phalcon_Assets_Filters_Jsmin.rst +++ b/zh/api/Phalcon_Assets_Filters_Jsmin.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Assets\\Filters\\Jsmin** :raw-html:`Source on GitHub` -Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. +Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be +replaced with spaces. Carriage returns will be replaced with linefeeds. +Most spaces and linefeeds will be removed. Methods diff --git a/zh/api/Phalcon_Assets_Inline.rst b/zh/api/Phalcon_Assets_Inline.rst index aed05dcb985b..ae2e53a55812 100644 --- a/zh/api/Phalcon_Assets_Inline.rst +++ b/zh/api/Phalcon_Assets_Inline.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Inline** :raw-html:`Source on GitHub` -Represents an inline asset +Represents an inline asset .. code-block:: php addCss('css/bootstrap.css'); - $assets->addCss('http://bootstrap.my-cdn.com/style.css', false); + $assets->addCss("css/bootstrap.css"); + $assets->addCss("http://bootstrap.my-cdn.com/style.css", false); @@ -58,14 +58,14 @@ Adds an inline Css to the 'css' collection public **addJs** (*mixed* $path, [*mixed* $local], [*mixed* $filter], [*mixed* $attributes]) -Adds a javascript resource to the 'js' collection +Adds a javascript resource to the 'js' collection .. code-block:: php addJs('scripts/jquery.js'); - $assets->addJs('http://jquery.my-cdn.com/jquery.js', false); + $assets->addJs("scripts/jquery.js"); + $assets->addJs("http://jquery.my-cdn.com/jquery.js", false); @@ -78,13 +78,15 @@ Adds an inline javascript to the 'js' collection public **addResourceByType** (*mixed* $type, :doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a resource by its type +Adds a resource by its type .. code-block:: php addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css')); + $assets->addResourceByType("css", + new \Phalcon\Assets\Resource\Css("css/style.css") + ); @@ -97,13 +99,15 @@ Adds an inline code by its type public **addResource** (:doc:`Phalcon\\Assets\\Resource ` $resource) -Adds a raw resource to the manager +Adds a raw resource to the manager .. code-block:: php addResource(new Phalcon\Assets\Resource('css', 'css/style.css')); + $assets->addResource( + new Phalcon\Assets\Resource("css", "css/style.css") + ); @@ -116,26 +120,26 @@ Adds a raw inline code to the manager public **set** (*mixed* $id, :doc:`Phalcon\\Assets\\Collection ` $collection) -Sets a collection in the Assets Manager +Sets a collection in the Assets Manager .. code-block:: php set('js', $collection); + $assets->set("js", $collection); public **get** (*mixed* $id) -Returns a collection by its id +Returns a collection by its id .. code-block:: php get('js'); + $scripts = $assets->get("js"); diff --git a/zh/api/Phalcon_Assets_Resource.rst b/zh/api/Phalcon_Assets_Resource.rst index 77aeb8ed09d2..9ecfabd7490e 100644 --- a/zh/api/Phalcon_Assets_Resource.rst +++ b/zh/api/Phalcon_Assets_Resource.rst @@ -6,13 +6,13 @@ Class **Phalcon\\Assets\\Resource** :raw-html:`Source on GitHub` -Represents an asset resource +Represents an asset resource .. code-block:: php ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/zh/api/Phalcon_Assets_Resource_Js.rst b/zh/api/Phalcon_Assets_Resource_Js.rst index dc1eaff96d8b..75a4665cd7b8 100644 --- a/zh/api/Phalcon_Assets_Resource_Js.rst +++ b/zh/api/Phalcon_Assets_Resource_Js.rst @@ -115,7 +115,8 @@ Sets the resource's target path public **getContent** ([*mixed* $basePath]) inherited from :doc:`Phalcon\\Assets\\Resource ` -Returns the content of the resource as an string Optionally a base path where the resource is located can be set +Returns the content of the resource as an string +Optionally a base path where the resource is located can be set diff --git a/zh/api/Phalcon_Cache_Backend.rst b/zh/api/Phalcon_Cache_Backend.rst index c16f74551d07..1c088c1e1eac 100644 --- a/zh/api/Phalcon_Cache_Backend.rst +++ b/zh/api/Phalcon_Cache_Backend.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Cache\\Backend** ========================================== +*implements* :doc:`Phalcon\\Cache\\BackendInterface ` + .. role:: raw-html(raw) :format: html @@ -78,3 +80,28 @@ Gets the last lifetime set +abstract public **get** (*mixed* $keyName, [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **save** ([*mixed* $keyName], [*mixed* $content], [*mixed* $lifetime], [*mixed* $stopBuffer]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **delete** (*mixed* $keyName) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **queryKeys** ([*mixed* $prefix]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + +abstract public **exists** ([*mixed* $keyName], [*mixed* $lifetime]) inherited from :doc:`Phalcon\\Cache\\BackendInterface ` + +... + + diff --git a/zh/api/Phalcon_Cache_Backend_Apc.rst b/zh/api/Phalcon_Cache_Backend_Apc.rst index b492046925e1..ecc7ac70f43e 100644 --- a/zh/api/Phalcon_Cache_Backend_Apc.rst +++ b/zh/api/Phalcon_Cache_Backend_Apc.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Apc** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an APC backend +Allows to cache output fragments, PHP data and raw data using an APC backend .. code-block:: php 172800 - ]); - - $cache = new Apc($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Apc; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Apc( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -45,19 +50,19 @@ Returns a cached content -public **save** ([*string* | *long* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* | *int* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the APC backend and stops the frontend -public *mixed* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of a given key, by number $value @@ -69,13 +74,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *long* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired @@ -85,6 +100,20 @@ public **flush** () Immediately invalidates all existing items. +.. code-block:: php + + "app-data"]); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); + + public **getFrontend** () inherited from :doc:`Phalcon\\Cache\\Backend ` diff --git a/zh/api/Phalcon_Cache_Backend_File.rst b/zh/api/Phalcon_Cache_Backend_File.rst index 05e1204c62e1..80978ff63bdc 100644 --- a/zh/api/Phalcon_Cache_Backend_File.rst +++ b/zh/api/Phalcon_Cache_Backend_File.rst @@ -10,38 +10,40 @@ Class **Phalcon\\Cache\\Backend\\File** :raw-html:`Source on GitHub` -Allows to cache output fragments using a file backend +Allows to cache output fragments using a file backend .. code-block:: php 172800 - ]; - - // Create an output cache - $frontCache = FrontOutput($frontOptions); - - // Set the cache directory - $backendOptions = [ - 'cacheDir' => '../app/cache/' - ]; - - // Create the File backend - $cache = new File($frontCache, $backendOptions); - - $content = $cache->start('my-cache'); - if ($content === null) { - echo '

', time(), '

'; - $cache->save(); - } else { - echo $content; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Output as FrontOutput; + + // Cache the file for 2 days + $frontendOptions = [ + "lifetime" => 172800, + ]; + + // Create an output cache + $frontCache = FrontOutput($frontOptions); + + // Set the cache directory + $backendOptions = [ + "cacheDir" => "../app/cache/", + ]; + + // Create the File backend + $cache = new File($frontCache, $backendOptions); + + $content = $cache->start("my-cache"); + + if ($content === null) { + echo "

", time(), "

"; + + $cache->save(); + } else { + echo $content; + } @@ -66,31 +68,41 @@ Stores cached content into the file backend and stops the frontend -public *boolean* **delete** (*int* | *string* $keyName) +public **delete** (*int* | *string* $keyName) Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*int* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** ([*string* | *int* $keyName], [*int* $value]) +public **increment** ([*string* | *int* $keyName], [*mixed* $value]) Increment of a given key, by number $value -public *mixed* **decrement** ([*string* | *int* $keyName], [*int* $value]) +public **decrement** ([*string* | *int* $keyName], [*mixed* $value]) Decrement of a given key, by number $value diff --git a/zh/api/Phalcon_Cache_Backend_Libmemcached.rst b/zh/api/Phalcon_Cache_Backend_Libmemcached.rst index 66979ec70c7d..be5e647aea01 100644 --- a/zh/api/Phalcon_Cache_Backend_Libmemcached.rst +++ b/zh/api/Phalcon_Cache_Backend_Libmemcached.rst @@ -10,40 +10,46 @@ Class **Phalcon\\Cache\\Backend\\Libmemcached** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used. +Allows to cache output fragments, PHP data or raw data to a libmemcached backend. +Per default persistent memcached connection pools are used. .. code-block:: php 172800 - ]); - - // Create the Cache setting memcached connection options - $cache = new Libmemcached($frontCache, [ - 'servers' => [ - [ - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1 - ], - ], - 'client' => [ - \Memcached::OPT_HASH => Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ] - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Libmemcached; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Libmemcached( + $frontCache, + [ + "servers" => [ + [ + "host" => "127.0.0.1", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -68,7 +74,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -80,25 +86,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) -Query the existing cached keys +Query the existing cached keys. +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) + + +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value @@ -106,17 +122,25 @@ Decrement of $keyName by given $value public **flush** () -Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. +Immediately invalidates all existing items. +Memcached does not support flush() per default. If you require flush() support, set $config["statsKey"]. +All modified keys are stored in "statsKey". Note: statsKey has a negative performance impact. .. code-block:: php "_PHCM"]); - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //'my-data' and all other used keys are deleted - $cache->flush(); + $cache = new \Phalcon\Cache\Backend\Libmemcached( + $frontCache, + [ + "statsKey" => "_PHCM", + ] + ); + + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // 'my-data' and all other used keys are deleted + $cache->flush(); diff --git a/zh/api/Phalcon_Cache_Backend_Memcache.rst b/zh/api/Phalcon_Cache_Backend_Memcache.rst index 7cf3a6b923e9..a3156dd1fbe6 100644 --- a/zh/api/Phalcon_Cache_Backend_Memcache.rst +++ b/zh/api/Phalcon_Cache_Backend_Memcache.rst @@ -10,32 +10,39 @@ Class **Phalcon\\Cache\\Backend\\Memcache** :raw-html:`Source on GitHub` -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 +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 Memcache($frontCache, [ - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -66,7 +73,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -78,25 +85,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *long* **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/zh/api/Phalcon_Cache_Backend_Memory.rst b/zh/api/Phalcon_Cache_Backend_Memory.rst index eb31091db858..76d5ff06c6d0 100644 --- a/zh/api/Phalcon_Cache_Backend_Memory.rst +++ b/zh/api/Phalcon_Cache_Backend_Memory.rst @@ -10,25 +10,25 @@ Class **Phalcon\\Cache\\Backend\\Memory** :raw-html:`Source on GitHub` -Stores content in memory. Data is lost when the request is finished +Stores content in memory. Data is lost when the request is finished .. code-block:: php save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Memory; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data + $frontCache = new FrontData(); + + $cache = new Memory($frontCache); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -41,7 +41,7 @@ Returns a cached content -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the backend and stops the frontend @@ -53,25 +53,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* | *int* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists and it hasn't expired -public *long* **increment** ([*string* $keyName], [*mixed* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public *long* **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/zh/api/Phalcon_Cache_Backend_Mongo.rst b/zh/api/Phalcon_Cache_Backend_Mongo.rst index 5e1bdd262b0c..882e46bd9361 100644 --- a/zh/api/Phalcon_Cache_Backend_Mongo.rst +++ b/zh/api/Phalcon_Cache_Backend_Mongo.rst @@ -10,32 +10,40 @@ Class **Phalcon\\Cache\\Backend\\Mongo** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a MongoDb 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 Mongo($frontCache, [ - 'server' => "mongodb://localhost", - 'db' => 'caches', - 'collection' => 'images' - ]); - - // Cache arbitrary data - $cache->save('my-data', file_get_contents('some-image.jpg')); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Mongo; + use Phalcon\Cache\Frontend\Base64; + + // Cache data for 2 days + $frontCache = new Base64( + [ + "lifetime" => 172800, + ] + ); + + // Create a MongoDB cache + $cache = new Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + // Cache arbitrary data + $cache->save( + "my-data", + file_get_contents("some-image.jpg") + ); + + // Get data + $data = $cache->get("my-data"); @@ -60,7 +68,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -72,13 +80,23 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired @@ -90,13 +108,13 @@ gc -public *mixed* **increment** (*int* | *string* $keyName, [*long* $value]) +public **increment** (*int* | *string* $keyName, [*mixed* $value]) Increment of a given key by $value -public *mixed* **decrement** (*int* | *string* $keyName, [*long* $value]) +public **decrement** (*int* | *string* $keyName, [*mixed* $value]) Decrement of a given key by $value diff --git a/zh/api/Phalcon_Cache_Backend_Redis.rst b/zh/api/Phalcon_Cache_Backend_Redis.rst index 1b049102edb2..04edad9f35ed 100644 --- a/zh/api/Phalcon_Cache_Backend_Redis.rst +++ b/zh/api/Phalcon_Cache_Backend_Redis.rst @@ -10,34 +10,41 @@ Class **Phalcon\\Cache\\Backend\\Redis** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter +Allows to cache output fragments, PHP data or raw data to a redis backend + +This adapter uses the special redis key "_PHCR" to store all the keys internally used by the adapter .. code-block:: php 172800 - ]); - - // Create the Cache setting redis connection options - $cache = new Redis($frontCache, [ - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false - 'index' => 0, - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Redis; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting redis connection options + $cache = new Redis( + $frontCache, + [ + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "index" => 0, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -62,10 +69,20 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend +.. code-block:: php + + save("my-key", $data); + + // Save data termlessly + $cache->save("my-key", $data, -1); + + public **delete** (*int* | *string* $keyName) @@ -74,25 +91,35 @@ Deletes a value from the cache by its key -public **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public **increment** ([*string* $keyName], [*long* $value]) +public **increment** ([*string* $keyName], [*mixed* $value]) Increment of given $keyName by $value -public **decrement** ([*string* $keyName], [*long* $value]) +public **decrement** ([*string* $keyName], [*mixed* $value]) Decrement of $keyName by given $value diff --git a/zh/api/Phalcon_Cache_Backend_Xcache.rst b/zh/api/Phalcon_Cache_Backend_Xcache.rst index f72940328044..577999fdcf8e 100644 --- a/zh/api/Phalcon_Cache_Backend_Xcache.rst +++ b/zh/api/Phalcon_Cache_Backend_Xcache.rst @@ -10,29 +10,34 @@ Class **Phalcon\\Cache\\Backend\\Xcache** :raw-html:`Source on GitHub` -Allows to cache output fragments, PHP data and raw data using an XCache backend +Allows to cache output fragments, PHP data and raw data using an XCache backend .. code-block:: php 172800 - ]); - - $cache = new Xcache($frontCache, [ - 'prefix' => 'app-data' - ]); - - // Cache arbitrary data - $cache->save('my-data', [1, 2, 3, 4, 5]); - - // Get data - $data = $cache->get('my-data'); + use Phalcon\Cache\Backend\Xcache; + use Phalcon\Cache\Frontend\Data as FrontData; + + // Cache data for 2 days + $frontCache = new FrontData( + [ + "lifetime" => 172800, + ] + ); + + $cache = new Xcache( + $frontCache, + [ + "prefix" => "app-data", + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -51,7 +56,7 @@ Returns a cached content -public **save** ([*int* | *string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*int* | *string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into the file backend and stops the frontend @@ -63,25 +68,35 @@ Deletes a value from the cache by its key -public *array* **queryKeys** ([*string* $prefix]) +public **queryKeys** ([*mixed* $prefix]) + +Query the existing cached keys. + +.. code-block:: php + + save("users-ids", [1, 2, 3]); + $cache->save("projects-ids", [4, 5, 6]); + + var_dump($cache->queryKeys("users")); // ["users-ids"] -Query the existing cached keys -public *boolean* **exists** ([*string* $keyName], [*long* $lifetime]) +public **exists** ([*string* $keyName], [*int* $lifetime]) Checks if cache exists and it isn't expired -public *mixed* **increment** (*string* $keyName, [*long* $value]) +public **increment** (*string* $keyName, [*mixed* $value]) Atomic increment of a given key, by number $value -public *mixed* **decrement** (*string* $keyName, [*long* $value]) +public **decrement** (*string* $keyName, [*mixed* $value]) Atomic decrement of a given key, by number $value diff --git a/zh/api/Phalcon_Cache_Frontend_Base64.rst b/zh/api/Phalcon_Cache_Frontend_Base64.rst index dd153275f311..5085c2db3d55 100644 --- a/zh/api/Phalcon_Cache_Frontend_Base64.rst +++ b/zh/api/Phalcon_Cache_Frontend_Base64.rst @@ -8,37 +8,49 @@ Class **Phalcon\\Cache\\Frontend\\Base64** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP's functions +Allows to cache data converting/deconverting them to base64. + +This adapter 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_get_contents('tmp-dir/some-image.jpg')); - } - - header('Content-Type: image/jpeg'); - echo $image; + + // Cache the files for 2 days using a Base64 frontend + $frontCache = new \Phalcon\Cache\Frontend\Base64( + [ + "lifetime" => 172800, + ] + ); + + //Create a MongoDB cache + $cache = new \Phalcon\Cache\Backend\Mongo( + $frontCache, + [ + "server" => "mongodb://localhost", + "db" => "caches", + "collection" => "images", + ] + ); + + $cacheKey = "some-image.jpg.cache"; + + // Try to get cached image + $image = $cache->get($cacheKey); + + if ($image === null) { + // Store the image in the cache + $cache->save( + $cacheKey, + file_get_contents("tmp-dir/some-image.jpg") + ); + } + + header("Content-Type: image/jpeg"); + + echo $image; @@ -81,13 +93,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/zh/api/Phalcon_Cache_Frontend_Data.rst b/zh/api/Phalcon_Cache_Frontend_Data.rst index 828cdcd66d99..5c4b043bce37 100644 --- a/zh/api/Phalcon_Cache_Frontend_Data.rst +++ b/zh/api/Phalcon_Cache_Frontend_Data.rst @@ -8,40 +8,54 @@ Class **Phalcon\\Cache\\Frontend\\Data** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form +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 File($frontCache, ['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(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots :) - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Data; + + // Cache the files for 2 days using a Data frontend + $frontCache = new Data( + [ + "lifetime" => 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $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( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/zh/api/Phalcon_Cache_Frontend_Igbinary.rst b/zh/api/Phalcon_Cache_Frontend_Igbinary.rst index 3c0ed5e3f5fb..08329a44aca3 100644 --- a/zh/api/Phalcon_Cache_Frontend_Igbinary.rst +++ b/zh/api/Phalcon_Cache_Frontend_Igbinary.rst @@ -10,40 +10,50 @@ Class **Phalcon\\Cache\\Frontend\\Igbinary** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using igbinary extension +Allows to cache native PHP data in a serialized form using igbinary extension .. code-block:: php 172800 - )); - + $frontCache = new \Phalcon\Cache\Frontend\Igbinary( + [ + "lifetime" => 172800, + ] + ); + // Create the component that will cache "Igbinary" 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/" - )); - + $cache = new \Phalcon\Cache\Backend\File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // Try to get cached records - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $robots = $cache->get($cacheKey); + if ($robots === null) { - - // $robots is null due to cache expiration or data do 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); + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } @@ -87,13 +97,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/zh/api/Phalcon_Cache_Frontend_Json.rst b/zh/api/Phalcon_Cache_Frontend_Json.rst index f0dff6f3fecb..e191a3cc67e3 100644 --- a/zh/api/Phalcon_Cache_Frontend_Json.rst +++ b/zh/api/Phalcon_Cache_Frontend_Json.rst @@ -8,31 +8,41 @@ Class **Phalcon\\Cache\\Frontend\\Json** :raw-html:`Source on GitHub` -Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP's functions As the data is encoded in JSON other systems accessing the same backend could process them +Allows to cache data converting/deconverting them to JSON. + +This adapter uses the json_encode/json_decode PHP's functions + +As the data is encoded in JSON other systems accessing the same backend could +process them .. code-block:: php 172800 - )); - - //Create the Cache setting memcached connection options - $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array( - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); - - //Cache arbitrary data - $cache->save('my-data', array(1, 2, 3, 4, 5)); - - //Get data - $data = $cache->get('my-data'); + + // Cache the data for 2 days + $frontCache = new \Phalcon\Cache\Frontend\Json( + [ + "lifetime" => 172800, + ] + ); + + // Create the Cache setting memcached connection options + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); + + // Cache arbitrary data + $cache->save("my-data", [1, 2, 3, 4, 5]); + + // Get data + $data = $cache->get("my-data"); @@ -75,13 +85,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/zh/api/Phalcon_Cache_Frontend_Msgpack.rst b/zh/api/Phalcon_Cache_Frontend_Msgpack.rst index 1da5a41e15b2..55adf0e9341c 100644 --- a/zh/api/Phalcon_Cache_Frontend_Msgpack.rst +++ b/zh/api/Phalcon_Cache_Frontend_Msgpack.rst @@ -10,43 +10,55 @@ Class **Phalcon\\Cache\\Frontend\\Msgpack** :raw-html:`Source on GitHub` -Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. +Allows to cache native PHP data in a serialized form using msgpack extension +This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension. .. code-block:: php 172800 - ]); - - // Create the component that will cache "Msgpack" 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 File($frontCache, [ - '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 do not exist - // Make the database call and populate the variable - $robots = Robots::find(['order' => 'id']); - - // Store it in the cache - $cache->save($cacheKey, $robots); - } - - // Use $robots - foreach ($robots as $robot) { - echo $robot->name, "\n"; - } + use Phalcon\Cache\Backend\File; + use Phalcon\Cache\Frontend\Msgpack; + + // Cache the files for 2 days using Msgpack frontend + $frontCache = new Msgpack( + [ + "lifetime" => 172800, + ] + ); + + // Create the component that will cache "Msgpack" 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 File( + $frontCache, + [ + "cacheDir" => "../app/cache/", + ] + ); + + $cacheKey = "robots_order_id.cache"; + + // Try to get cached records + $robots = $cache->get($cacheKey); + + if ($robots === null) { + // $robots is null due to cache expiration or data do not exist + // Make the database call and populate the variable + $robots = Robots::find( + [ + "order" => "id", + ] + ); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } diff --git a/zh/api/Phalcon_Cache_Frontend_None.rst b/zh/api/Phalcon_Cache_Frontend_None.rst index ede9356be7ec..5dca8830c3e9 100644 --- a/zh/api/Phalcon_Cache_Frontend_None.rst +++ b/zh/api/Phalcon_Cache_Frontend_None.rst @@ -8,39 +8,47 @@ Class **Phalcon\\Cache\\Frontend\\None** :raw-html:`Source on GitHub` -Discards any kind of frontend data input. This frontend does not have expiration time or any other options +Discards any kind of frontend data input. This frontend does not have expiration time or any other options .. code-block:: php "localhost", - "port" => "11211" - )); - + $cache = new \Phalcon\Cache\Backend\Memcache( + $frontCache, + [ + "host" => "localhost", + "port" => "11211", + ] + ); + + $cacheKey = "robots_order_id.cache"; + // This Frontend always return the data as it's returned by the backend - $cacheKey = 'robots_order_id.cache'; - $robots = $cache->get($cacheKey); + $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); + // 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( + [ + "order" => "id", + ] + ); + + $cache->save($cacheKey, $robots); } - + // Use $robots :) foreach ($robots as $robot) { - echo $robot->name, "\n"; + echo $robot->name, "\n"; } diff --git a/zh/api/Phalcon_Cache_Frontend_Output.rst b/zh/api/Phalcon_Cache_Frontend_Output.rst index 517584eb2cef..59f138d94945 100644 --- a/zh/api/Phalcon_Cache_Frontend_Output.rst +++ b/zh/api/Phalcon_Cache_Frontend_Output.rst @@ -8,7 +8,7 @@ Class **Phalcon\\Cache\\Frontend\\Output** :raw-html:`Source on GitHub` -Allows to cache output fragments captured with ob_* functions +Allows to cache output fragments captured with ob_* functions .. code-block:: php @@ -20,27 +20,36 @@ Allows to cache output fragments captured with ob_* functions * use Phalcon\Cache\Frontend\Output; * * // Create an Output frontend. Cache the files for 2 days - * $frontCache = new Output(['lifetime' => 172800])); + * $frontCache = new Output( + * [ + * "lifetime" => 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 File($frontCache, ['cacheDir' => '../app/cache/']); + * $cache = new File( + * $frontCache, + * [ + * "cacheDir" => "../app/cache/", + * ] + * ); * * // Get/Set the cache file to ../app/cache/my-cache.html - * $content = $cache->start('my-cache.html'); + * $content = $cache->start("my-cache.html"); * * // If $content is null then the content will be generated for the cache * if (null === $content) { * // Print date and time - * echo date('r'); + * echo date("r"); * * // Generate a link to the sign-up action * echo Tag::linkTo( * [ - * 'user/signup', - * 'Sign Up', - * 'class' => 'signup-button' + * "user/signup", + * "Sign Up", + * "class" => "signup-button", * ] * ); * @@ -93,13 +102,13 @@ Stops output frontend -public *string* **beforeStore** (*mixed* $data) +public **beforeStore** (*mixed* $data) Serializes data before storing them -public *mixed* **afterRetrieve** (*mixed* $data) +public **afterRetrieve** (*mixed* $data) Unserializes data after retrieval diff --git a/zh/api/Phalcon_Cache_Multiple.rst b/zh/api/Phalcon_Cache_Multiple.rst index 765e69b52246..7193b6a49ae6 100644 --- a/zh/api/Phalcon_Cache_Multiple.rst +++ b/zh/api/Phalcon_Cache_Multiple.rst @@ -6,48 +6,65 @@ Class **Phalcon\\Cache\\Multiple** :raw-html:`Source on GitHub` -Allows to read to chained backend adapters writing to multiple backends +Allows to read to chained backend adapters writing to multiple backends .. code-block:: php 3600 - )); - - $fastFrontend = new DataFrontend(array( - "lifetime" => 86400 - )); - - $slowFrontend = new DataFrontend(array( - "lifetime" => 604800 - )); - - //Backends are registered from the fastest to the slower - $cache = new Multiple(array( - new ApcCache($ultraFastFrontend, array( - "prefix" => 'cache', - )), - new MemcacheCache($fastFrontend, array( - "prefix" => 'cache', - "host" => "localhost", - "port" => "11211" - )), - new FileCache($slowFrontend, array( - "prefix" => 'cache', - "cacheDir" => "../app/cache/" - )) - )); - - //Save, saves in every backend - $cache->save('my-key', $data); + use Phalcon\Cache\Frontend\Data as DataFrontend; + use Phalcon\Cache\Multiple; + use Phalcon\Cache\Backend\Apc as ApcCache; + use Phalcon\Cache\Backend\Memcache as MemcacheCache; + use Phalcon\Cache\Backend\File as FileCache; + + $ultraFastFrontend = new DataFrontend( + [ + "lifetime" => 3600, + ] + ); + + $fastFrontend = new DataFrontend( + [ + "lifetime" => 86400, + ] + ); + + $slowFrontend = new DataFrontend( + [ + "lifetime" => 604800, + ] + ); + + //Backends are registered from the fastest to the slower + $cache = new Multiple( + [ + new ApcCache( + $ultraFastFrontend, + [ + "prefix" => "cache", + ] + ), + new MemcacheCache( + $fastFrontend, + [ + "prefix" => "cache", + "host" => "localhost", + "port" => "11211", + ] + ), + new FileCache( + $slowFrontend, + [ + "prefix" => "cache", + "cacheDir" => "../app/cache/", + ] + ), + ] + ); + + //Save, saves in every backend + $cache->save("my-key", $data); @@ -66,19 +83,19 @@ Adds a backend -public *mixed* **get** (*string* | *int* $keyName, [*long* $lifetime]) +public *mixed* **get** (*string* | *int* $keyName, [*int* $lifetime]) Returns a cached content reading the internal backends -public **start** (*string* | *int* $keyName, [*long* $lifetime]) +public **start** (*string* | *int* $keyName, [*int* $lifetime]) Starts every backend -public **save** ([*string* $keyName], [*string* $content], [*long* $lifetime], [*boolean* $stopBuffer]) +public **save** ([*string* $keyName], [*string* $content], [*int* $lifetime], [*boolean* $stopBuffer]) Stores cached content into all backends and stops the frontend @@ -90,7 +107,7 @@ Deletes a value from each backend -public *boolean* **exists** ([*string* | *int* $keyName], [*long* $lifetime]) +public **exists** ([*string* | *int* $keyName], [*int* $lifetime]) Checks if cache exists in at least one backend diff --git a/zh/api/Phalcon_Cli_Console.rst b/zh/api/Phalcon_Cli_Console.rst index cd9ab25296fe..92c2597a8ba6 100644 --- a/zh/api/Phalcon_Cli_Console.rst +++ b/zh/api/Phalcon_Cli_Console.rst @@ -18,18 +18,20 @@ Methods public **addModules** (*array* $modules) -Merge modules with the existing ones +Merge modules with the existing ones .. code-block:: php addModules(array( - 'admin' => array( - 'className' => 'Multiple\Admin\Module', - 'path' => '../apps/admin/Module.php' - ) - )); + $application->addModules( + [ + "admin" => [ + "className" => "Multiple\\Admin\\Module", + "path" => "../apps/admin/Module.php", + ], + ] + ); @@ -66,24 +68,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/zh/api/Phalcon_Cli_Dispatcher.rst b/zh/api/Phalcon_Cli_Dispatcher.rst index 8bc8e09a5d04..b886098cfbc5 100644 --- a/zh/api/Phalcon_Cli_Dispatcher.rst +++ b/zh/api/Phalcon_Cli_Dispatcher.rst @@ -10,23 +10,25 @@ Class **Phalcon\\Cli\\Dispatcher** :raw-html:`Source on GitHub` -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. +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(); + + $dispatcher->setDi($di); + + $dispatcher->setTaskName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + + $handle = $dispatcher->dispatch(); @@ -86,7 +88,7 @@ Handles a user exception public **getLastTask** () -Returns the lastest dispatched controller +Returns the latest dispatched controller @@ -277,13 +279,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/zh/api/Phalcon_Cli_Router.rst b/zh/api/Phalcon_Cli_Router.rst index cdfffd44bcef..08c685d252b9 100644 --- a/zh/api/Phalcon_Cli_Router.rst +++ b/zh/api/Phalcon_Cli_Router.rst @@ -8,18 +8,25 @@ Class **Phalcon\\Cli\\Router** :raw-html:`Source on GitHub` -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 +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( - 'module' => 'main', - 'task' => 'videos', - 'action' => 'process' - )); + + $router->handle( + [ + "module" => "main", + "task" => "videos", + "action" => "process", + ] + ); + echo $router->getTaskName(); @@ -65,16 +72,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults(array( - 'module' => 'common', - 'action' => 'index' - )); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -87,26 +97,26 @@ Handles routing information received from command-line arguments public :doc:`Phalcon\\Cli\\Router\\Route ` **add** (*string* $pattern, [*string/array* $paths]) -Adds a route to the router +Adds a route to the router .. code-block:: php add('/about', 'About::main'); + $router->add("/about", "About::main"); public **getModuleName** () -Returns proccesed module name +Returns processed module name public **getTaskName** () -Returns proccesed task name +Returns processed task name diff --git a/zh/api/Phalcon_Cli_Router_Route.rst b/zh/api/Phalcon_Cli_Router_Route.rst index 8a00e4cc44c1..409d5fc2aa02 100644 --- a/zh/api/Phalcon_Cli_Router_Route.rst +++ b/zh/api/Phalcon_Cli_Router_Route.rst @@ -49,22 +49,27 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public :doc:`Phalcon\\Cli\\Router\\Route ` **beforeMatch** (*callback* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched diff --git a/zh/api/Phalcon_Cli_Task.rst b/zh/api/Phalcon_Cli_Task.rst index 5430cce73762..55d5cdb30235 100644 --- a/zh/api/Phalcon_Cli_Task.rst +++ b/zh/api/Phalcon_Cli_Task.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Cli\\Task** :raw-html:`Source on GitHub` -Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method +Every command-line task should extend this class that encapsulates all the task functionality + +A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. +The Task class should at least have a "mainAction" method .. code-block:: php @@ -18,18 +21,16 @@ Every command-line task should extend this class that encapsulates all the task class HelloTask extends \Phalcon\Cli\Task { - - // This action will be executed by default - public function mainAction() - { - - } - - public function findAction() - { - - } - + // This action will be executed by default + public function mainAction() + { + + } + + public function findAction() + { + + } } diff --git a/zh/api/Phalcon_Config.rst b/zh/api/Phalcon_Config.rst index c84777e23144..5d4dc7326950 100644 --- a/zh/api/Phalcon_Config.rst +++ b/zh/api/Phalcon_Config.rst @@ -8,26 +8,30 @@ Class **Phalcon\\Config** :raw-html:`Source on GitHub` -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. +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", - "dbname" => "test_db" - ), - "phalcon" => array( - "controllersDir" => "../app/controllers/", - "modelsDir" => "../app/models/", - "viewsDir" => "../app/views/" - ) - )); + $config = new \Phalcon\Config( + [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ] + ); @@ -42,113 +46,129 @@ Phalcon\\Config constructor public **offsetExists** (*mixed* $index) -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/zh/api/Phalcon_Config_Adapter_Ini.rst b/zh/api/Phalcon_Config_Adapter_Ini.rst index 80c55dd624fb..96d34a93d11e 100644 --- a/zh/api/Phalcon_Config_Adapter_Ini.rst +++ b/zh/api/Phalcon_Config_Adapter_Ini.rst @@ -10,41 +10,50 @@ Class **Phalcon\\Config\\Adapter\\Ini** :raw-html:`Source on GitHub` -Reads ini files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads ini files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: ini phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Ini("path/config.ini"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; - PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor: +PHP constants may also be parsed in the ini file, so if you define a constant +as an ini value before calling the constructor, the constant's value will be +integrated into the results. To use it this way you must specify the optional +second parameter as INI_SCANNER_NORMAL when calling the constructor: .. code-block:: php _parseIniString('path.hello.world', 'value for last key'); - - // result - [ - 'path' => [ - 'hello' => [ - 'world' => 'value for last key', - ], - ], - ]; + $this->_parseIniString("path.hello.world", "value for last key"); + // result + [ + "path" => [ + "hello" => [ + "world" => "value for last key", + ], + ], + ]; -private **_cast** (*mixed* $ini) + +protected **_cast** (*mixed* $ini) We have to cast values manually because parse_ini_file() has a poor implementation. @@ -87,113 +96,129 @@ We have to cast values manually because parse_ini_file() has a poor implementati public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/zh/api/Phalcon_Config_Adapter_Json.rst b/zh/api/Phalcon_Config_Adapter_Json.rst index 15f8dab21f3d..96900f581be0 100644 --- a/zh/api/Phalcon_Config_Adapter_Json.rst +++ b/zh/api/Phalcon_Config_Adapter_Json.rst @@ -10,23 +10,26 @@ Class **Phalcon\\Config\\Adapter\\Json** :raw-html:`Source on GitHub` -Reads JSON files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads JSON files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php phalcon->baseuri; - echo $config->models->metadata; + $config = new Phalcon\Config\Adapter\Json("path/config.json"); + + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -41,113 +44,129 @@ Phalcon\\Config\\Adapter\\Json constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/zh/api/Phalcon_Config_Adapter_Php.rst b/zh/api/Phalcon_Config_Adapter_Php.rst index 3a13c6c2963c..65d77e250347 100644 --- a/zh/api/Phalcon_Config_Adapter_Php.rst +++ b/zh/api/Phalcon_Config_Adapter_Php.rst @@ -10,37 +10,41 @@ Class **Phalcon\\Config\\Adapter\\Php** :raw-html:`Source on GitHub` -Reads php files and converts them to Phalcon\\Config objects. Given the next configuration file: +Reads php files and converts them to Phalcon\\Config objects. + +Given the next configuration file: .. code-block:: php array( - 'adapter' => 'Mysql', - 'host' => 'localhost', - 'username' => 'scott', - 'password' => 'cheetah', - 'dbname' => 'test_db' - ), - - 'phalcon' => array( - 'controllersDir' => '../app/controllers/', - 'modelsDir' => '../app/models/', - 'viewsDir' => '../app/views/' - )); - - You can read it as follows: + + return [ + "database" => [ + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "dbname" => "test_db", + ], + "phalcon" => [ + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ], + ]; + +You can read it as follows: .. code-block:: php phalcon->controllersDir; - echo $config->database->username; + $config = new \Phalcon\Config\Adapter\Php("path/config.php"); + + echo $config->phalcon->controllersDir; + echo $config->database->username; @@ -55,113 +59,129 @@ Phalcon\\Config\\Adapter\\Php constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/zh/api/Phalcon_Config_Adapter_Yaml.rst b/zh/api/Phalcon_Config_Adapter_Yaml.rst index c45aaf905d50..491694889acf 100644 --- a/zh/api/Phalcon_Config_Adapter_Yaml.rst +++ b/zh/api/Phalcon_Config_Adapter_Yaml.rst @@ -10,35 +10,43 @@ Class **Phalcon\\Config\\Adapter\\Yaml** :raw-html:`Source on GitHub` -Reads YAML files and converts them to Phalcon\\Config objects. Given the following configuration file: +Reads YAML files and converts them to Phalcon\\Config objects. + +Given the following configuration file: .. code-block:: php function($value) { - return APPROOT . $value; - } - ]); - - echo $config->phalcon->controllersDir; - echo $config->phalcon->baseuri; - echo $config->models->metadata; + define( + "APPROOT", + dirname(__DIR__) + ); + + $config = new \Phalcon\Config\Adapter\Yaml( + "path/config.yaml", + [ + "!approot" => function($value) { + return APPROOT . $value; + }, + ] + ); + + echo $config->phalcon->controllersDir; + echo $config->phalcon->baseuri; + echo $config->models->metadata; @@ -53,113 +61,129 @@ Phalcon\\Config\\Adapter\\Yaml constructor public **offsetExists** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Allows to check whether an attribute is defined using the array-syntax +Allows to check whether an attribute is defined using the array-syntax .. code-block:: php ` -Gets an attribute from the configuration, if the attribute isn't defined returns null If the value is exactly null or is not defined the default value will be used instead +Gets an attribute from the configuration, if the attribute isn't defined returns null +If the value is exactly null or is not defined the default value will be used instead .. code-block:: php get('controllersDir', '../app/controllers/'); + echo $config->get("controllersDir", "../app/controllers/"); public **offsetGet** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Gets an attribute using the array-syntax +Gets an attribute using the array-syntax .. code-block:: php ` -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php 'Sqlite'); + $config["database"] = [ + "type" => "Sqlite", + ]; public **offsetUnset** (*mixed* $index) inherited from :doc:`Phalcon\\Config ` -Unsets an attribute using the array-syntax +Unsets an attribute using the array-syntax .. code-block:: php ` $config) inherited from :doc:`Phalcon\\Config ` -Merges a configuration into the current one +Merges a configuration into the current one .. code-block:: php array('host' => 'localhost'))); - $globalConfig->merge($config2); + $appConfig = new \Phalcon\Config( + [ + "database" => [ + "host" => "localhost", + ], + ] + ); + + $globalConfig->merge($appConfig); public **toArray** () inherited from :doc:`Phalcon\\Config ` -Converts recursively the object to an array +Converts recursively the object to an array .. code-block:: php toArray()); + print_r( + $config->toArray() + ); public **count** () inherited from :doc:`Phalcon\\Config ` -Returns the count of properties set in the config +Returns the count of properties set in the config .. code-block:: php count(); + print $config->count(); diff --git a/zh/api/Phalcon_Crypt.rst b/zh/api/Phalcon_Crypt.rst index d07b1d2cb2fa..fd5d1f2fcb95 100644 --- a/zh/api/Phalcon_Crypt.rst +++ b/zh/api/Phalcon_Crypt.rst @@ -8,19 +8,19 @@ Class **Phalcon\\Crypt** :raw-html:`Source on GitHub` -Provides encryption facilities to phalcon applications +Provides encryption facilities to phalcon applications .. code-block:: php encrypt($text, $key); - + echo $crypt->decrypt($encrypted, $key); @@ -89,7 +89,7 @@ If the function detects that the text was not padded, it will return it unmodifi public **encrypt** (*mixed* $text, [*mixed* $key]) -Encrypts a text +Encrypts a text .. code-block:: php @@ -102,7 +102,7 @@ Encrypts a text public **decrypt** (*mixed* $text, [*mixed* $key]) -Decrypts an encrypted text +Decrypts an encrypted text .. code-block:: php diff --git a/zh/api/Phalcon_Db.rst b/zh/api/Phalcon_Db.rst index 0863e6299ce0..f195104f8717 100644 --- a/zh/api/Phalcon_Db.rst +++ b/zh/api/Phalcon_Db.rst @@ -6,7 +6,14 @@ Abstract class **Phalcon\\Db** :raw-html:`Source on GitHub` -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 +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 @@ -15,25 +22,29 @@ Phalcon\\Db and its related classes provide a simple SQL database interface for use Phalcon\Db; use Phalcon\Db\Exception; use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection; - + try { - - $connection = new MysqlConnection(array( - 'host' => '192.168.0.11', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => '3306', - )); - - $result = $connection->query("SELECT * FROM robots LIMIT 5"); - $result->setFetchMode(Db::FETCH_NUM); - while ($robot = $result->fetch()) { - print_r($robot); - } - + $connection = new MysqlConnection( + [ + "host" => "192.168.0.11", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => "3306", + ] + ); + + $result = $connection->query( + "SELECT * FROM robots LIMIT 5" + ); + + $result->setFetchMode(Db::FETCH_NUM); + + while ($robot = $result->fetch()) { + print_r($robot); + } } catch (Exception $e) { - echo $e->getMessage(), PHP_EOL; + echo $e->getMessage(), PHP_EOL; } diff --git a/zh/api/Phalcon_Db_Adapter.rst b/zh/api/Phalcon_Db_Adapter.rst index 7e9daa07de03..cb7724489427 100644 --- a/zh/api/Phalcon_Db_Adapter.rst +++ b/zh/api/Phalcon_Db_Adapter.rst @@ -1,7 +1,7 @@ Abstract class **Phalcon\\Db\\Adapter** ======================================= -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html @@ -64,18 +64,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -83,25 +83,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -109,18 +116,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -128,79 +138,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -208,43 +220,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -257,39 +292,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -392,65 +431,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -493,36 +542,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -559,7 +622,7 @@ Active SQL statement in the object public **getRealSQLStatement** () -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -569,3 +632,68 @@ Active SQL statement in the object +abstract public **connect** ([*array* $descriptor]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **query** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **execute** (*mixed* $sqlStatement, [*mixed* $placeholders], [*mixed* $dataTypes]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **affectedRows** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **lastInsertId** ([*mixed* $sequenceName]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **begin** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **rollback** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **commit** ([*mixed* $nesting]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **getInternalHandler** () inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/zh/api/Phalcon_Db_Adapter_Pdo.rst b/zh/api/Phalcon_Db_Adapter_Pdo.rst index 3e62ba3615eb..187e1dacd1dc 100644 --- a/zh/api/Phalcon_Db_Adapter_Pdo.rst +++ b/zh/api/Phalcon_Db_Adapter_Pdo.rst @@ -3,30 +3,30 @@ Abstract class **Phalcon\\Db\\Adapter\\Pdo** *extends* abstract class :doc:`Phalcon\\Db\\Adapter ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; + + $connection = new Mysql($config); @@ -41,168 +41,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) -This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) -Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +public **close** () - -public *string* **escapeIdentifier** (*string* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); - +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -233,14 +280,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -301,18 +352,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -320,25 +371,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -346,18 +404,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -365,79 +426,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -445,43 +508,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -494,39 +580,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -629,65 +719,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -730,36 +830,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -796,7 +910,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters @@ -806,3 +920,8 @@ Active SQL statement in the object +abstract public **describeColumns** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\AdapterInterface ` + +... + + diff --git a/zh/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/zh/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index fcbf407d0423..46195b1392df 100644 --- a/zh/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/zh/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -3,91 +3,77 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Mysql database system +Specific functions for the Mysql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 3306, - 'username' => 'sigma', - 'password' => 'secret' - ]; - - $connection = new Mysql($config); + use Phalcon\Db\Adapter\Pdo\Mysql; + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret", + ]; - -Methods -------- - -public **escapeIdentifier** (*mixed* $identifier) - -Escapes a column/table/schema name - -.. code-block:: php - - escapeIdentifier('my_table'); // `my_table` - echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name` - -.. code-block:: php - - describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); @@ -100,154 +86,215 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **connect** ([*array* $descriptor]) inherited from :doc:`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. +This method is automatically called in \\Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. .. code-block:: php 'localhost', - 'username' => 'sigma', - 'password' => 'secret', - 'dbname' => 'blog', - 'port' => 3306, - ]); - - // Reconnect - $connection->connect(); + use Phalcon\Db\Adapter\Pdo\Mysql; + + // Make a connection + $connection = new Mysql( + [ + "host" => "localhost", + "username" => "sigma", + "password" => "secret", + "dbname" => "blog", + "port" => 3306, + ] + ); + + // Reconnect + $connection->connect(); public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; + $connection->execute( + "DELETE FROM robots" + ); + + echo $connection->affectedRows(), " were deleted"; public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -278,14 +325,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -346,18 +397,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -365,25 +416,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -391,18 +449,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -410,79 +471,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -490,43 +553,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -539,39 +625,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -674,39 +764,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -749,36 +845,50 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -815,7 +925,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/zh/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/zh/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index 74386b53650b..cbdecf79c1bf 100644 --- a/zh/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/zh/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -3,30 +3,30 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Postgresql database system +Specific functions for the Postgresql database system .. code-block:: php 'localhost', - 'dbname' => 'blog', - 'port' => 5432, - 'username' => 'postgres', - 'password' => 'secret' - ]; - - $connection = new Postgresql($config); + use Phalcon\Db\Adapter\Pdo\Postgresql; + + $config = [ + "host" => "localhost", + "dbname" => "blog", + "port" => 5432, + "username" => "postgres", + "password" => "secret", + ]; + + $connection = new Postgresql($config); @@ -35,19 +35,22 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); @@ -72,18 +75,26 @@ Check whether the database system requires an explicit value for identity column public **getDefaultIdValue** () -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -102,143 +113,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - + $connection->execute( + "DELETE FROM robots" + ); + echo $connection->affectedRows(), " were deleted"; -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a column/table/schema name -.. code-block:: php - - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -269,14 +324,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -337,18 +396,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -356,25 +415,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -382,18 +448,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -401,79 +470,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -481,43 +552,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name .. code-block:: php delete( - "robots", - "id = 101" - ); - - //Next SQL sentence is generated - DELETE FROM `robots` WHERE `id` = 101 + $escapedTable = $connection->escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -530,39 +624,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -653,65 +751,75 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public :doc:`Phalcon\\Db\\Index `\ [] **describeIndexes** (*string* $table, [*string* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); public **describeReferences** (*mixed* $table, [*mixed* $schema]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Lists table references +Lists table references .. code-block:: php describeReferences('robots_parts')); + print_r( + $connection->describeReferences("robots_parts") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -754,18 +862,24 @@ Returns the savepoint name to use for nested transactions public **getDefaultValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue() + ], + [ + "name", + "year", + ] + ); @@ -790,7 +904,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/zh/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/zh/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index 3e775356fe24..748da97dc14b 100644 --- a/zh/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/zh/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -3,22 +3,26 @@ Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** *extends* abstract class :doc:`Phalcon\\Db\\Adapter\\Pdo ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Db\\AdapterInterface ` +*implements* :doc:`Phalcon\\Db\\AdapterInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Specific functions for the Sqlite database system +Specific functions for the Sqlite database system .. code-block:: php '/tmp/test.sqlite']); + use Phalcon\Db\Adapter\Pdo\Sqlite; + + $connection = new Sqlite( + [ + "dbname" => "/tmp/test.sqlite", + ] + ); @@ -27,32 +31,37 @@ Methods public **connect** ([*array* $descriptor]) -This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. +Call it when you need to restore a database connection. public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Returns an array of Phalcon\\Db\\Column objects describing a table +Returns an array of Phalcon\\Db\\Column objects describing a table .. code-block:: php describeColumns("posts")); + print_r( + $connection->describeColumns("posts") + ); public :doc:`Phalcon\\Db\\IndexInterface `\ [] **describeIndexes** (*string* $table, [*string* $schema]) -Lists table indexes +Lists table indexes .. code-block:: php describeIndexes('robots_parts')); + print_r( + $connection->describeIndexes("robots_parts") + ); @@ -71,18 +80,24 @@ Check whether the database system requires an explicit value for identity column public **getDefaultValue** () -Returns the default value to make the RBDM use the default value declared in the table definition +Returns the default value to make the RBDM use the default value declared in the table definition .. code-block:: php insert( - "robots", - array("Astro Boy", $connection->getDefaultValue()), - array("name", "year") - ); + // Inserting a new robot with a valid default value for the column 'year' + $success = $connection->insert( + "robots", + [ + "Astro Boy", + $connection->getDefaultValue(), + ], + [ + "name", + "year", + ] + ); @@ -95,143 +110,187 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo public **prepare** (*mixed* $sqlStatement) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns a PDO prepared statement to be executed with 'executePrepared' +Returns a PDO prepared statement to be executed with 'executePrepared' .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public `PDOStatement `_ **executePrepared** (`PDOStatement `_ $statement, *array* $placeholders, *array* $dataTypes) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Executes a prepared statement binding. This function uses integer indexes starting from zero +Executes a prepared statement binding. This function uses integer indexes starting from zero .. code-block:: php prepare('SELECT * FROM robots WHERE name = :name'); - $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]); + use Phalcon\Db\Column; + + $statement = $db->prepare( + "SELECT * FROM robots WHERE name = :name" + ); + + $result = $connection->executePrepared( + $statement, + [ + "name" => "Voltron", + ], + [ + "name" => Column::BIND_PARAM_INT, + ] + ); public **query** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 is returning rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server is returning rows .. code-block:: php query("SELECT * FROM robots WHERE type='mechanical'"); - $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + // Querying data + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = 'mechanical'" + ); + + $resultset = $connection->query( + "SELECT * FROM robots WHERE type = ?", + [ + "mechanical", + ] + ); public **execute** (*mixed* $sqlStatement, [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`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 doesn't return any rows +Sends SQL statements to the database server returning the success state. +Use this method only when the SQL statement sent to the server doesn't return any rows .. code-block:: php execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); - $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + // Inserting data + $success = $connection->execute( + "INSERT INTO robots VALUES (1, 'Astro Boy')" + ); + + $success = $connection->execute( + "INSERT INTO robots VALUES (?, ?)", + [ + 1, + "Astro Boy", + ] + ); public **affectedRows** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system +Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system .. code-block:: php execute("DELETE FROM robots"); - echo $connection->affectedRows(), ' were deleted'; - - - + $connection->execute( + "DELETE FROM robots" + ); -public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` - -Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends - - - -public *string* **escapeIdentifier** (*string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` + echo $connection->affectedRows(), " were deleted"; -Escapes a column/table/schema name -.. code-block:: php - escapeIdentifier('robots'); - $escapedTable = $connection->escapeIdentifier(['store', 'robots']); +public **close** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` +Closes the active connection returning success. Phalcon automatically closes and destroys +active connections when the request ends public **escapeString** (*mixed* $str) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Escapes a value to avoid SQL injections according to the active charset in the connection +Escapes a value to avoid SQL injections according to the active charset in the connection .. code-block:: php escapeString('some dangerous value'); + $escapedStr = $connection->escapeString("some dangerous value"); public **convertBoundParams** (*mixed* $sql, [*array* $params]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Converts bound parameters such as :name: or ?1 into PDO bind params ? +Converts bound parameters such as :name: or ?1 into PDO bind params ? .. code-block:: php convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender'))); + print_r( + $connection->convertBoundParams( + "SELECT * FROM robots WHERE name = :name:", + [ + "Bender", + ] + ) + ); public *int* | *boolean* **lastInsertId** ([*string* $sequenceName]) inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement +Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement .. code-block:: php insert( - "robots", - array("Astro Boy", 1952), - array("name", "year") - ); - - //Getting the generated id - $id = $connection->lastInsertId(); + // Inserting a new robot + $success = $connection->insert( + "robots", + [ + "Astro Boy", + 1952, + ], + [ + "name", + "year", + ] + ); + + // Getting the generated id + $id = $connection->lastInsertId(); @@ -262,14 +321,18 @@ Returns the current transaction nesting level public **isUnderTransaction** () inherited from :doc:`Phalcon\\Db\\Adapter\\Pdo ` -Checks whether the connection is under a transaction +Checks whether the connection is under a transaction .. code-block:: php begin(); - var_dump($connection->isUnderTransaction()); //true + + // true + var_dump( + $connection->isUnderTransaction() + ); @@ -330,18 +393,18 @@ Returns internal dialect instance public **fetchOne** (*mixed* $sqlQuery, [*mixed* $fetchMode], [*mixed* $bindParams], [*mixed* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the first row in a SQL query result +Returns the first row in a SQL query result .. code-block:: php fetchOne("SELECT * FROM robots"); print_r($robot); - - //Getting first robot with associative indexes only - $robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + + // Getting first robot with associative indexes only + $robot = $connection->fetchOne("SELECT * FROM robots", \Phalcon\Db::FETCH_ASSOC); print_r($robot); @@ -349,25 +412,32 @@ Returns the first row in a SQL query result public *array* **fetchAll** (*string* $sqlQuery, [*int* $fetchMode], [*array* $bindParams], [*array* $bindTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Dumps the complete result of a query into an array +Dumps the complete result of a query into an array .. code-block:: php fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + // Getting all robots with associative indexes only + $robots = $connection->fetchAll( + "SELECT * FROM robots", + \Phalcon\Db::FETCH_ASSOC + ); + foreach ($robots as $robot) { - print_r($robot); + print_r($robot); } - - //Getting all robots that contains word "robot" withing the name - $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name", - Phalcon\Db::FETCH_ASSOC, - array('name' => '%robot%') - ); - foreach($robots as $robot){ - print_r($robot); + + // Getting all robots that contains word "robot" withing the name + $robots = $connection->fetchAll( + "SELECT * FROM robots WHERE name LIKE :name", + \Phalcon\Db::FETCH_ASSOC, + [ + "name" => "%robot%", + ] + ); + foreach($robots as $robot) { + print_r($robot); } @@ -375,18 +445,21 @@ Dumps the complete result of a query into an array public *string* | ** **fetchColumn** (*string* $sqlQuery, [*array* $placeholders], [*int* | *string* $column]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the n'th field of first row in a SQL query result +Returns the n'th field of first row in a SQL query result .. code-block:: php fetchColumn("SELECT count(*) FROM robots"); print_r($robotsCount); - - //Getting name of last edited robot - $robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1); + + // Getting name of last edited robot + $robot = $connection->fetchColumn( + "SELECT id, name FROM robots order by modified desc", + 1 + ); print_r($robot); @@ -394,79 +467,81 @@ Returns the n'th field of first row in a SQL query result public *boolean* **insert** (*string* | *array* $table, *array* $values, [*array* $fields], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RDBMS SQL syntax +Inserts data into a table using custom RDBMS 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); + // Inserting a new robot + $success = $connection->insert( + "robots", + ["Astro Boy", 1952], + ["name", "year"] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **insertAsDict** (*string* $table, *array* $data, [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Inserts data into a table using custom RBDM SQL syntax +Inserts data into a table using custom RBDM SQL syntax .. code-block:: php insertAsDict( - "robots", - array( - "name" => "Astro Boy", - "year" => 1952 - ) - ); - - //Next SQL sentence is sent to the database system - INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + // Inserting a new robot + $success = $connection->insertAsDict( + "robots", + [ + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); public *boolean* **update** (*string* | *array* $table, *array* $fields, *array* $values, [*string* | *array* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax +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 - - //Updating existing robot with array condition and $dataTypes - $success = $connection->update( - "robots", - array("name"), - array("New Astro Boy"), - array( - 'conditions' => "id = ?", - 'bind' => array($some_unsafe_id), - 'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param - ), - array(PDO::PARAM_STR) - ); + // Updating existing robot + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + "id = 101" + ); + + // Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + // Updating existing robot with array condition and $dataTypes + $success = $connection->update( + "robots", + ["name"], + ["New Astro Boy"], + [ + "conditions" => "id = ?", + "bind" => [$some_unsafe_id], + "bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param + ], + [ + PDO::PARAM_STR + ] + ); Warning! If $whereCondition is string it not escaped. @@ -474,43 +549,66 @@ Warning! If $whereCondition is string it not escaped. public *boolean* **updateAsDict** (*string* $table, *array* $data, [*string* $whereCondition], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax +Updates data on a table using custom RBDM SQL syntax +Another, more convenient syntax .. code-block:: php updateAsDict( - "robots", - array( - "name" => "New Astro Boy" - ), - "id = 101" - ); - - //Next SQL sentence is sent to the database system - UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + // Updating existing robot + $success = $connection->updateAsDict( + "robots", + [ + "name" => "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* | *array* $table, [*string* $whereCondition], [*array* $placeholders], [*array* $dataTypes]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Deletes data from a table using custom RBDM SQL syntax +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 + // Deleting existing robot + $success = $connection->delete( + "robots", + "id = 101" + ); + + // Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public **escapeIdentifier** (*array* | *string* $identifier) inherited from :doc:`Phalcon\\Db\\Adapter ` + +Escapes a column/table/schema name + +.. code-block:: php + + escapeIdentifier( + "robots" + ); + + $escapedTable = $connection->escapeIdentifier( + [ + "store", + "robots", + ] + ); @@ -523,39 +621,43 @@ Gets a list of columns public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Adapter ` -Appends a LIMIT clause to $sqlQuery argument +Appends a LIMIT clause to $sqlQuery argument .. code-block:: php limit("SELECT * FROM robots", 5); + echo $connection->limit("SELECT * FROM robots", 5); public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("blog", "posts")); + var_dump( + $connection->tableExists("blog", "posts") + ); public **viewExists** (*mixed* $viewName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Generates SQL checking for the existence of a schema.view +Generates SQL checking for the existence of a schema.view .. code-block:: php viewExists("active_users", "posts")); + var_dump( + $connection->viewExists("active_users", "posts") + ); @@ -658,39 +760,45 @@ Returns the SQL column definition from a column public **listTables** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all tables on a database +List all tables on a database .. code-block:: php listTables("blog")); + print_r( + $connection->listTables("blog") + ); public **listViews** ([*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -List all views on a database +List all views on a database .. code-block:: php listViews("blog")); + print_r( + $connection->listViews("blog") + ); public **tableOptions** (*mixed* $tableName, [*mixed* $schemaName]) inherited from :doc:`Phalcon\\Db\\Adapter ` -Gets creation options from a table +Gets creation options from a table .. code-block:: php tableOptions('robots')); + print_r( + $connection->tableOptions("robots") + ); @@ -733,18 +841,26 @@ Returns the savepoint name to use for nested transactions public **getDefaultIdValue** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Returns the default identity value to be inserted in an identity column +Returns the default identity value to be inserted in an identity column .. code-block:: php insert( - "robots", - array($connection->getDefaultIdValue(), "Astro Boy", 1952), - array("id", "name", "year") - ); + // Inserting a new robot with a valid default value for the column 'id' + $success = $connection->insert( + "robots", + [ + $connection->getDefaultIdValue(), + "Astro Boy", + 1952, + ], + [ + "id", + "name", + "year", + ] + ); @@ -775,7 +891,7 @@ Active SQL statement in the object public **getRealSQLStatement** () inherited from :doc:`Phalcon\\Db\\Adapter ` -Active SQL statement in the object without replace bound paramters +Active SQL statement in the object without replace bound parameters diff --git a/zh/api/Phalcon_Db_Column.rst b/zh/api/Phalcon_Db_Column.rst index 30e9833f0037..afccbd2f714b 100644 --- a/zh/api/Phalcon_Db_Column.rst +++ b/zh/api/Phalcon_Db_Column.rst @@ -8,26 +8,29 @@ Class **Phalcon\\Db\\Column** :raw-html:`Source on GitHub` -Allows to define columns to be used on create or alter table operations +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); + + // Column definition + $column = new Column( + "id", + [ + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ] + ); + + // Add column to existing table + $connection->addColumn("robots", null, $column); diff --git a/zh/api/Phalcon_Db_Dialect.rst b/zh/api/Phalcon_Db_Dialect.rst index 921b35af1933..5809f05336e1 100644 --- a/zh/api/Phalcon_Db_Dialect.rst +++ b/zh/api/Phalcon_Db_Dialect.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Db\\Dialect** :raw-html:`Source on GitHub` -This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax +This is the base class to each database dialect. This implements +common methods to transform intermediate code into its RDBMS related syntax Methods @@ -40,58 +41,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/zh/api/Phalcon_Db_Dialect_Mysql.rst b/zh/api/Phalcon_Db_Dialect_Mysql.rst index cd899fb89df4..2f51516bfee5 100644 --- a/zh/api/Phalcon_Db_Dialect_Mysql.rst +++ b/zh/api/Phalcon_Db_Dialect_Mysql.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -202,58 +207,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/zh/api/Phalcon_Db_Dialect_Postgresql.rst b/zh/api/Phalcon_Db_Dialect_Postgresql.rst index 2e382429bdcf..ad6fc41bda8b 100644 --- a/zh/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/zh/api/Phalcon_Db_Dialect_Postgresql.rst @@ -84,7 +84,7 @@ Generates SQL to create a table public **dropTable** (*mixed* $tableName, [*mixed* $schemaName], [*mixed* $ifExists]) -Generates SQL to drop a view +Generates SQL to drop a table @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -170,6 +175,11 @@ Generates the SQL to describe the table creation options +protected **_castDefault** (:doc:`Phalcon\\Db\\ColumnInterface ` $column) + +... + + protected **_getTableOptions** (*array* $definition) ... @@ -201,58 +211,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/zh/api/Phalcon_Db_Dialect_Sqlite.rst b/zh/api/Phalcon_Db_Dialect_Sqlite.rst index 3fff656f9601..1f22ccc8176a 100644 --- a/zh/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/zh/api/Phalcon_Db_Dialect_Sqlite.rst @@ -102,14 +102,15 @@ Generates SQL to drop a view public **tableExists** (*mixed* $tableName, [*mixed* $schemaName]) -Generates SQL checking for the existence of a schema.table +Generates SQL checking for the existence of a schema.table .. code-block:: php tableExists("posts", "blog"); - echo $dialect->tableExists("posts"); + echo $dialect->tableExists("posts", "blog"); + + echo $dialect->tableExists("posts"); @@ -122,26 +123,30 @@ Generates SQL checking for the existence of a schema.view public **describeColumns** (*mixed* $table, [*mixed* $schema]) -Generates SQL describing a table +Generates SQL describing a table .. code-block:: php describeColumns("posts")); + print_r( + $dialect->describeColumns("posts") + ); public **listTables** ([*mixed* $schemaName]) -List all tables in database +List all tables in database .. code-block:: php listTables("blog")) + print_r( + $dialect->listTables("blog") + ); @@ -154,13 +159,15 @@ Generates the SQL to list all views of a schema or user public **listIndexesSql** (*mixed* $table, [*mixed* $schema], [*mixed* $keyName]) -Generates the SQL to get query list of indexes +Generates the SQL to get query list of indexes .. code-block:: php listIndexesSql("blog")) + print_r( + $dialect->listIndexesSql("blog") + ); @@ -215,58 +222,63 @@ Escape identifiers public **limit** (*mixed* $sqlQuery, *mixed* $number) inherited from :doc:`Phalcon\\Db\\Dialect ` -Generates the SQL for LIMIT clause +Generates the SQL for LIMIT clause .. code-block:: php limit('SELECT * FROM robots', 10); - echo $sql; // SELECT * FROM robots LIMIT 10 - - $sql = $dialect->limit('SELECT * FROM robots', [10, 50]); - echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 + $sql = $dialect->limit("SELECT * FROM robots", 10); + echo $sql; // SELECT * FROM robots LIMIT 10 + + $sql = $dialect->limit("SELECT * FROM robots", [10, 50]); + echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50 public **forUpdate** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a FOR UPDATE clause +Returns a SQL modified with a FOR UPDATE clause .. code-block:: php forUpdate('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots FOR UPDATE + $sql = $dialect->forUpdate("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots FOR UPDATE public **sharedLock** (*mixed* $sqlQuery) inherited from :doc:`Phalcon\\Db\\Dialect ` -Returns a SQL modified with a LOCK IN SHARE MODE clause +Returns a SQL modified with a LOCK IN SHARE MODE clause .. code-block:: php sharedLock('SELECT * FROM robots'); - echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE + $sql = $dialect->sharedLock("SELECT * FROM robots"); + echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE final public **getColumnList** (*array* $columnList, [*mixed* $escapeChar], [*mixed* $bindCounts]) inherited from :doc:`Phalcon\\Db\\Dialect ` -Gets a list of columns with escaped identifiers +Gets a list of columns with escaped identifiers .. code-block:: php getColumnList(array('column1', 'column')); + echo $dialect->getColumnList( + [ + "column1", + "column", + ] + ); diff --git a/zh/api/Phalcon_Db_Index.rst b/zh/api/Phalcon_Db_Index.rst index 227b766ccbe8..415a456a64bd 100644 --- a/zh/api/Phalcon_Db_Index.rst +++ b/zh/api/Phalcon_Db_Index.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Db\\Index** :raw-html:`Source on GitHub` -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 +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 Methods diff --git a/zh/api/Phalcon_Db_Profiler.rst b/zh/api/Phalcon_Db_Profiler.rst index e8859d1ebdb4..9f1dac4bdf32 100644 --- a/zh/api/Phalcon_Db_Profiler.rst +++ b/zh/api/Phalcon_Db_Profiler.rst @@ -6,27 +6,30 @@ Class **Phalcon\\Db\\Profiler** :raw-html:`Source on GitHub` -Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications. +Instances of Phalcon\\Db can generate execution profiles +on SQL statements sent to the relational database. Profiled +information includes execution time in milliseconds. +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 + + // Execute a SQL statement $connection->query($sql); - - //Get the last profile in the profiler + + // 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"; diff --git a/zh/api/Phalcon_Db_RawValue.rst b/zh/api/Phalcon_Db_RawValue.rst index e49a858dc99b..7fc6d43dad0a 100644 --- a/zh/api/Phalcon_Db_RawValue.rst +++ b/zh/api/Phalcon_Db_RawValue.rst @@ -6,15 +6,19 @@ Class **Phalcon\\Db\\RawValue** :raw-html:`Source on GitHub` -This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value. +This class allows to insert/update raw data without quoting or formatting. + +The next example shows how to use the MySQL now() function as a field value. .. code-block:: php email = 'andres@phalconphp.com'; - $subscriber->createdAt = new \Phalcon\Db\RawValue('now()'); + + $subscriber->email = "andres@phalconphp.com"; + $subscriber->createdAt = new \Phalcon\Db\RawValue("now()"); + $subscriber->save(); diff --git a/zh/api/Phalcon_Db_Reference.rst b/zh/api/Phalcon_Db_Reference.rst index 5a3fe05264e0..932290f7733e 100644 --- a/zh/api/Phalcon_Db_Reference.rst +++ b/zh/api/Phalcon_Db_Reference.rst @@ -8,18 +8,27 @@ Class **Phalcon\\Db\\Reference** :raw-html:`Source on GitHub` -Allows to define reference constraints on tables +Allows to define reference constraints on tables .. code-block:: php "invoicing", - 'referencedTable' => "products", - 'columns' => array("product_type", "product_code"), - 'referencedColumns' => array("type", "code") - )); + $reference = new \Phalcon\Db\Reference( + "field_fk", + [ + "referencedSchema" => "invoicing", + "referencedTable" => "products", + "columns" => [ + "product_type", + "product_code", + ], + "referencedColumns" => [ + "type", + "code", + ], + ] + ); diff --git a/zh/api/Phalcon_Db_Result_Pdo.rst b/zh/api/Phalcon_Db_Result_Pdo.rst index 6b44bdd731a5..966109f2fb47 100644 --- a/zh/api/Phalcon_Db_Result_Pdo.rst +++ b/zh/api/Phalcon_Db_Result_Pdo.rst @@ -8,16 +8,20 @@ Class **Phalcon\\Db\\Result\\Pdo** :raw-html:`Source on GitHub` -Encapsulates the resultset internals +Encapsulates the resultset internals .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - $result->setFetchMode(Phalcon\Db::FETCH_NUM); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = $result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -33,22 +37,28 @@ Phalcon\\Db\\Result\\Pdo constructor public **execute** () -Allows to execute 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 +Allows to execute 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 **fetch** ([*mixed* $fetchStyle], [*mixed* $cursorOrientation], [*mixed* $cursorOffset]) -Fetches an array/object 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 +Fetches an array/object 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_OBJ); + + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); + while ($robot = $result->fetch()) { - echo $robot->name; + echo $robot->name; } @@ -56,16 +66,21 @@ Fetches an array/object of strings that corresponds to the fetched row, or FALSE public **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 +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); + + $result->setFetchMode( + \Phalcon\Db::FETCH_NUM + ); + while ($robot = result->fetchArray()) { - print_r($robot); + print_r($robot); } @@ -73,13 +88,17 @@ Returns an array of strings that corresponds to the fetched row, or FALSE if the public **fetchAll** ([*mixed* $fetchStyle], [*mixed* $fetchArgument], [*mixed* $ctorArgs]) -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 +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"); + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + $robots = $result->fetchAll(); @@ -87,52 +106,69 @@ Returns an array of arrays containing all the records in the result This method public **numRows** () -Gets number of rows returned by a resultset +Gets number of rows returned by a resultset .. code-block:: php query("SELECT * FROM robots ORDER BY name"); - echo 'There are ', $result->numRows(), ' rows in the resultset'; + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + echo "There are ", $result->numRows(), " rows in the resultset"; public **dataSeek** (*mixed* $number) -Moves internal resultset cursor to another position letting us to fetch a certain row +Moves internal resultset 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->fetch(); // Fetch third row + $result = $connection->query( + "SELECT * FROM robots ORDER BY name" + ); + + // Move to third row on result + $result->dataSeek(2); + + // Fetch third row + $row = $result->fetch(); public **setFetchMode** (*mixed* $fetchMode, [*mixed* $colNoOrClassNameOrObject], [*mixed* $ctorargs]) -Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetch() .. 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); - - //Return an object - $result->setFetchMode(\Phalcon\Db::FETCH_OBJ); + // Return array with integer indexes + $result->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 + ); + + // Return an object + $result->setFetchMode( + \Phalcon\Db::FETCH_OBJ + ); diff --git a/zh/api/Phalcon_Debug.rst b/zh/api/Phalcon_Debug.rst index d92551a4b0f5..6b91ad0a31a3 100644 --- a/zh/api/Phalcon_Debug.rst +++ b/zh/api/Phalcon_Debug.rst @@ -32,7 +32,8 @@ Set if files part of the backtrace must be shown in the output public **setShowFileFragment** (*mixed* $showFileFragment) -Sets if files must be completely opened and showed in the output or just the fragment related to the exception +Sets if files must be completely opened and showed in the output +or just the fragment related to the exception diff --git a/zh/api/Phalcon_Debug_Dump.rst b/zh/api/Phalcon_Debug_Dump.rst index 3d35ad49f661..92cd9e1b15b0 100644 --- a/zh/api/Phalcon_Debug_Dump.rst +++ b/zh/api/Phalcon_Debug_Dump.rst @@ -6,23 +6,25 @@ Class **Phalcon\\Debug\\Dump** :raw-html:`Source on GitHub` -Dumps information about a variable(s) +Dumps information about a variable(s) .. code-block:: php variable($foo, "foo"); + $foo = 123; + + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); @@ -57,7 +59,7 @@ Get style for type -public **setStyles** ([*mixed* $styles]) +public **setStyles** ([*array* $styles]) Set styles for vars type @@ -77,46 +79,53 @@ Prepare an HTML string of information about a single variable. public **variable** (*mixed* $variable, [*mixed* $name]) -Returns an HTML string of information about a single variable. +Returns an HTML string of information about a single variable. .. code-block:: php variable($foo, "foo"); + echo (new \Phalcon\Debug\Dump())->variable($foo, "foo"); public **variables** () -Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag. +Returns an HTML string of debugging information about any number of +variables, each wrapped in a "pre" tag. .. code-block:: php "value"]; - $baz = new stdClass(); - echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); + $foo = "string"; + $bar = ["key" => "value"]; + $baz = new stdClass(); + + echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz); public **toJson** (*mixed* $variable) -Returns an JSON string of information about a single variable. +Returns an JSON string of information about a single variable. .. code-block:: php "value"]; - echo (new \Phalcon\Debug\Dump())->toJson($foo); - $foo = new stdClass(); - $foo->bar = 'buz'; - echo (new \Phalcon\Debug\Dump())->toJson($foo); + $foo = [ + "key" => "value", + ]; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); + + $foo = new stdClass(); + $foo->bar = "buz"; + + echo (new \Phalcon\Debug\Dump())->toJson($foo); diff --git a/zh/api/Phalcon_Di.rst b/zh/api/Phalcon_Di.rst index b8c1e7c21c92..9c74d79c2739 100644 --- a/zh/api/Phalcon_Di.rst +++ b/zh/api/Phalcon_Di.rst @@ -8,23 +8,41 @@ Class **Phalcon\\Di** :raw-html:`Source on GitHub` -Phalcon\\Di is a component that implements Dependency Injection/Service 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. 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. +Phalcon\\Di is a component that implements Dependency Injection/Service 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. + +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. .. code-block:: php set("request", "Phalcon\Http\Request", true); - - //Using an anonymous function - $di->set("request", function(){ - return new \Phalcon\Http\Request(); - }, true); - - $request = $di->getRequest(); + use Phalcon\Di; + use Phalcon\Http\Request; + + $di = new Di(); + + // Using a string definition + $di->set("request", Request::class, true); + + // Using an anonymous function + $di->setShared( + "request", + function () { + return new Request(); + } + ); + + $request = $di->getRequest(); @@ -63,13 +81,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -99,7 +120,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -127,9 +149,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) +public **offsetSet** (*mixed* $name, *mixed* $definition) -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -142,7 +164,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -159,7 +181,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) +public **__call** (*mixed* $method, [*mixed* $arguments]) Magic method to get or set services using setters/getters diff --git a/zh/api/Phalcon_Di_FactoryDefault.rst b/zh/api/Phalcon_Di_FactoryDefault.rst index c0755449e2d1..fa2efd203098 100644 --- a/zh/api/Phalcon_Di_FactoryDefault.rst +++ b/zh/api/Phalcon_Di_FactoryDefault.rst @@ -10,7 +10,9 @@ Class **Phalcon\\Di\\FactoryDefault** :raw-html:`Source on GitHub` -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 providing a full stack framework +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 providing a full stack framework Methods @@ -48,13 +50,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +89,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +118,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +133,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +150,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/zh/api/Phalcon_Di_FactoryDefault_Cli.rst b/zh/api/Phalcon_Di_FactoryDefault_Cli.rst index 0c1fd2c616f8..6bc613806a53 100644 --- a/zh/api/Phalcon_Di_FactoryDefault_Cli.rst +++ b/zh/api/Phalcon_Di_FactoryDefault_Cli.rst @@ -10,7 +10,10 @@ Class **Phalcon\\Di\\FactoryDefault\\Cli** :raw-html:`Source on GitHub` -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 +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 @@ -48,13 +51,16 @@ Registers an "always shared" service in the services container public **remove** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Removes a service in the services container It also removes any shared instance created for the service +Removes a service in the services container +It also removes any shared instance created for the service public **attempt** (*mixed* $name, *mixed* $definition, [*mixed* $shared]) inherited from :doc:`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 +Attempts to register a service in the services container +Only is successful if a service hasn't been registered previously +with the same name @@ -84,7 +90,8 @@ Resolves the service based on its configuration public *mixed* **getShared** (*string* $name, [*array* $parameters]) inherited from :doc:`Phalcon\\Di ` -Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance +Resolves a service, the resolved service is stored in the DI, subsequent +requests for this service will return the same instance @@ -112,9 +119,9 @@ Check if a service is registered using the array syntax -public *boolean* **offsetSet** (*string* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` +public **offsetSet** (*mixed* $name, *mixed* $definition) inherited from :doc:`Phalcon\\Di ` -Allows to register a shared service using the array syntax +Allows to register a shared service using the array syntax .. code-block:: php @@ -127,7 +134,7 @@ Allows to register a shared service using the array syntax public **offsetGet** (*mixed* $name) inherited from :doc:`Phalcon\\Di ` -Allows to obtain a shared service using the array syntax +Allows to obtain a shared service using the array syntax .. code-block:: php @@ -144,7 +151,7 @@ Removes a service from the services container using the array syntax -public **__call** (*string* $method, [*array* $arguments]) inherited from :doc:`Phalcon\\Di ` +public **__call** (*mixed* $method, [*mixed* $arguments]) inherited from :doc:`Phalcon\\Di ` Magic method to get or set services using setters/getters diff --git a/zh/api/Phalcon_Di_Injectable.rst b/zh/api/Phalcon_Di_Injectable.rst index 6e70e8d8cb37..d4f17c92d19a 100644 --- a/zh/api/Phalcon_Di_Injectable.rst +++ b/zh/api/Phalcon_Di_Injectable.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Di\\Injectable** :raw-html:`Source on GitHub` -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 +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 diff --git a/zh/api/Phalcon_Di_Service.rst b/zh/api/Phalcon_Di_Service.rst index 923683f09c64..3f6dc4d7f646 100644 --- a/zh/api/Phalcon_Di_Service.rst +++ b/zh/api/Phalcon_Di_Service.rst @@ -8,14 +8,18 @@ Class **Phalcon\\Di\\Service** :raw-html:`Source on GitHub` -Represents individually a service in the services container +Represents individually a service in the services container .. code-block:: php resolve(); + $service = new \Phalcon\Di\Service( + "request", + "Phalcon\\Http\\Request" + ); + + $request = service->resolve(); .. code-block:: php diff --git a/zh/api/Phalcon_Dispatcher.rst b/zh/api/Phalcon_Dispatcher.rst index 35a8198767e0..14e17cfb147b 100644 --- a/zh/api/Phalcon_Dispatcher.rst +++ b/zh/api/Phalcon_Dispatcher.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Dispatcher** :raw-html:`Source on GitHub` -This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. This class can't be instantiated directly, you can use it to create your own dispatchers. +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\Cli\\Dispatcher. +This class can't be instantiated directly, you can use it to create your own dispatchers. Constants @@ -193,13 +194,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/zh/api/Phalcon_Escaper.rst b/zh/api/Phalcon_Escaper.rst index 9a7b5dff02eb..38c6b827cd2c 100644 --- a/zh/api/Phalcon_Escaper.rst +++ b/zh/api/Phalcon_Escaper.rst @@ -8,14 +8,19 @@ Class **Phalcon\\Escaper** :raw-html:`Source on GitHub` -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. +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 @@ -25,13 +30,13 @@ Methods public **setEncoding** (*mixed* $encoding) -Sets the encoding to be used by the escaper +Sets the encoding to be used by the escaper .. code-block:: php setEncoding('utf-8'); + $escaper->setEncoding("utf-8"); @@ -44,33 +49,34 @@ Returns the internal encoding used by the escaper public **setHtmlQuoteType** (*mixed* $quoteType) -Sets the HTML quoting type for htmlspecialchars +Sets the HTML quoting type for htmlspecialchars .. code-block:: php setHtmlQuoteType(ENT_XHTML); + $escaper->setHtmlQuoteType(ENT_XHTML); public **setDoubleEncode** (*mixed* $doubleEncode) -Sets the double_encode to be used by the escaper +Sets the double_encode to be used by the escaper .. code-block:: php setDoubleEncode(false); + $escaper->setDoubleEncode(false); final public **detectEncoding** (*mixed* $str) -Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() +Detect the character encoding of a string to be handled by an encoder +Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding() diff --git a/zh/api/Phalcon_Events_Event.rst b/zh/api/Phalcon_Events_Event.rst index d42a9ee0b2a5..4f95d29bf37d 100644 --- a/zh/api/Phalcon_Events_Event.rst +++ b/zh/api/Phalcon_Events_Event.rst @@ -40,31 +40,49 @@ Phalcon\\Events\\Event constructor public **setData** ([*mixed* $data]) -Sets event data +Sets event data. public **setType** (*mixed* $type) -Sets event type +Sets event type. public **stop** () -Stops the event preventing propagation +Stops the event preventing propagation. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + public **isStopped** () -Check whether the event is currently stopped +Check whether the event is currently stopped. public **isCancelable** () -Check whether the event is cancelable +Check whether the event is cancelable. + +.. code-block:: php + + isCancelable()) { + $event->stop(); + } + diff --git a/zh/api/Phalcon_Events_Manager.rst b/zh/api/Phalcon_Events_Manager.rst index ef60a98269be..cf2e621bf034 100644 --- a/zh/api/Phalcon_Events_Manager.rst +++ b/zh/api/Phalcon_Events_Manager.rst @@ -8,7 +8,9 @@ Class **Phalcon\\Events\\Manager** :raw-html:`Source on GitHub` -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. +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 @@ -40,13 +42,15 @@ Returns if priorities are enabled public **collectResponses** (*mixed* $collect) -Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire +Tells the event manager if it needs to collect all the responses returned by every +registered listener in a single fire public **isCollecting** () -Check if the events manager is collecting all all the responses returned by every registered listener in a single fire +Check if the events manager is collecting all all the responses returned by every +registered listener in a single fire @@ -70,13 +74,13 @@ Internal handler to call a queue of events public *mixed* **fire** (*string* $eventType, *object* $source, [*mixed* $data], [*boolean* $cancelable]) -Fires an event in the events manager causing the active listeners to be notified about it +Fires an event in the events manager causing the active listeners to be notified about it .. code-block:: php fire('db', $connection); + $eventsManager->fire("db", $connection); diff --git a/zh/api/Phalcon_Filter.rst b/zh/api/Phalcon_Filter.rst index f96f3bb37b37..c4a6c87c3eb0 100644 --- a/zh/api/Phalcon_Filter.rst +++ b/zh/api/Phalcon_Filter.rst @@ -8,13 +8,16 @@ Class **Phalcon\\Filter** :raw-html:`Source on GitHub` -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 +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" diff --git a/zh/api/Phalcon_Flash.rst b/zh/api/Phalcon_Flash.rst index 80983e65b995..0f3465dbbdb2 100644 --- a/zh/api/Phalcon_Flash.rst +++ b/zh/api/Phalcon_Flash.rst @@ -1,21 +1,21 @@ Abstract class **Phalcon\\Flash** ================================= -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\FlashInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -Shows HTML notifications related to different circumstances. Classes can be stylized using CSS +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"); + $flash->success("The record was successfully deleted"); + $flash->error("Cannot open the file"); @@ -84,65 +84,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); @@ -153,3 +153,8 @@ Clears accumulated messages when implicit flush is disabled +abstract public **message** (*mixed* $type, *mixed* $message) inherited from :doc:`Phalcon\\FlashInterface ` + +... + + diff --git a/zh/api/Phalcon_Flash_Direct.rst b/zh/api/Phalcon_Flash_Direct.rst index 94fed7171560..acb58ea9eebc 100644 --- a/zh/api/Phalcon_Flash_Direct.rst +++ b/zh/api/Phalcon_Flash_Direct.rst @@ -90,65 +90,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/zh/api/Phalcon_Flash_Session.rst b/zh/api/Phalcon_Flash_Session.rst index f5205dfa4333..c64033e999d6 100644 --- a/zh/api/Phalcon_Flash_Session.rst +++ b/zh/api/Phalcon_Flash_Session.rst @@ -120,65 +120,65 @@ Set an array with CSS classes to format the messages public **error** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML error message +Shows a HTML error message .. code-block:: php error('This is an error'); + $flash->error("This is an error"); public **notice** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML notice/information message +Shows a HTML notice/information message .. code-block:: php notice('This is an information'); + $flash->notice("This is an information"); public **success** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML success message +Shows a HTML success message .. code-block:: php success('The process was finished successfully'); + $flash->success("The process was finished successfully"); public **warning** (*mixed* $message) inherited from :doc:`Phalcon\\Flash ` -Shows a HTML warning message +Shows a HTML warning message .. code-block:: php warning('Hey, this is important'); + $flash->warning("Hey, this is important"); public *string* | *void* **outputMessage** (*mixed* $type, *string* | *array* $message) inherited from :doc:`Phalcon\\Flash ` -Outputs a message formatting it with HTML +Outputs a message formatting it with HTML .. code-block:: php outputMessage('error', message); + $flash->outputMessage("error", $message); diff --git a/zh/api/Phalcon_Forms_Element.rst b/zh/api/Phalcon_Forms_Element.rst index dcd61de52682..5ea3b054a418 100644 --- a/zh/api/Phalcon_Forms_Element.rst +++ b/zh/api/Phalcon_Forms_Element.rst @@ -82,7 +82,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -154,7 +155,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -172,7 +174,8 @@ Returns the element value public **getMessages** () -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_Check.rst b/zh/api/Phalcon_Forms_Element_Check.rst index a216f03d7622..d6479dc71302 100644 --- a/zh/api/Phalcon_Forms_Element_Check.rst +++ b/zh/api/Phalcon_Forms_Element_Check.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_Date.rst b/zh/api/Phalcon_Forms_Element_Date.rst index 81a1eda61726..00e6a0f10d8d 100644 --- a/zh/api/Phalcon_Forms_Element_Date.rst +++ b/zh/api/Phalcon_Forms_Element_Date.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_Email.rst b/zh/api/Phalcon_Forms_Element_Email.rst index b90039addd71..a591d491e8fd 100644 --- a/zh/api/Phalcon_Forms_Element_Email.rst +++ b/zh/api/Phalcon_Forms_Element_Email.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_File.rst b/zh/api/Phalcon_Forms_Element_File.rst index 5fa14af9e61d..49a753015a49 100644 --- a/zh/api/Phalcon_Forms_Element_File.rst +++ b/zh/api/Phalcon_Forms_Element_File.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_Hidden.rst b/zh/api/Phalcon_Forms_Element_Hidden.rst index 865e96c21a03..d343e5d3f723 100644 --- a/zh/api/Phalcon_Forms_Element_Hidden.rst +++ b/zh/api/Phalcon_Forms_Element_Hidden.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_Numeric.rst b/zh/api/Phalcon_Forms_Element_Numeric.rst index 0214703ea27d..5e2893c593d2 100644 --- a/zh/api/Phalcon_Forms_Element_Numeric.rst +++ b/zh/api/Phalcon_Forms_Element_Numeric.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_Password.rst b/zh/api/Phalcon_Forms_Element_Password.rst index bf43f7bcce71..42bb4e717ed5 100644 --- a/zh/api/Phalcon_Forms_Element_Password.rst +++ b/zh/api/Phalcon_Forms_Element_Password.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_Radio.rst b/zh/api/Phalcon_Forms_Element_Radio.rst index fbe29302401f..e348099128af 100644 --- a/zh/api/Phalcon_Forms_Element_Radio.rst +++ b/zh/api/Phalcon_Forms_Element_Radio.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_Select.rst b/zh/api/Phalcon_Forms_Element_Select.rst index 4934232ef278..1cc474977b6b 100644 --- a/zh/api/Phalcon_Forms_Element_Select.rst +++ b/zh/api/Phalcon_Forms_Element_Select.rst @@ -108,7 +108,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -180,7 +181,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -198,7 +200,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_Submit.rst b/zh/api/Phalcon_Forms_Element_Submit.rst index 03f54dd10995..10944c96fdba 100644 --- a/zh/api/Phalcon_Forms_Element_Submit.rst +++ b/zh/api/Phalcon_Forms_Element_Submit.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_Text.rst b/zh/api/Phalcon_Forms_Element_Text.rst index b0b3a56334a6..641d9cabe310 100644 --- a/zh/api/Phalcon_Forms_Element_Text.rst +++ b/zh/api/Phalcon_Forms_Element_Text.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Element_TextArea.rst b/zh/api/Phalcon_Forms_Element_TextArea.rst index 8e4b2c75ca0b..2eb102d4d813 100644 --- a/zh/api/Phalcon_Forms_Element_TextArea.rst +++ b/zh/api/Phalcon_Forms_Element_TextArea.rst @@ -90,7 +90,8 @@ Returns the validators registered for the element public **prepareAttributes** ([*array* $attributes], [*mixed* $useChecked]) inherited from :doc:`Phalcon\\Forms\\Element ` -Returns an array of prepared attributes for Phalcon\\Tag helpers according to the element parameters +Returns an array of prepared attributes for Phalcon\\Tag helpers +according to the element parameters @@ -162,7 +163,8 @@ Generate the HTML to label the element public :doc:`Phalcon\\Forms\\ElementInterface ` **setDefault** (*mixed* $value) inherited from :doc:`Phalcon\\Forms\\Element ` -Sets a default value in case the form does not use an entity or there is no value available for the element in _POST +Sets a default value in case the form does not use an entity +or there is no value available for the element in _POST @@ -180,7 +182,8 @@ Returns the element value public **getMessages** () inherited from :doc:`Phalcon\\Forms\\Element ` -Returns the messages that belongs to the element The element needs to be attached to a form +Returns the messages that belongs to the element +The element needs to be attached to a form diff --git a/zh/api/Phalcon_Forms_Manager.rst b/zh/api/Phalcon_Forms_Manager.rst index e6715b90de2d..437ae903b218 100644 --- a/zh/api/Phalcon_Forms_Manager.rst +++ b/zh/api/Phalcon_Forms_Manager.rst @@ -12,7 +12,7 @@ Class **Phalcon\\Forms\\Manager** Methods ------- -public :doc:`Phalcon\\Forms\\Form ` **create** ([*string* $name], [*object* $entity]) +public **create** (*string* $name, [*object* $entity]) Creates a form registering it in the forms manager diff --git a/zh/api/Phalcon_Http_Cookie.rst b/zh/api/Phalcon_Http_Cookie.rst index 404c0124a896..747f0b4525e0 100644 --- a/zh/api/Phalcon_Http_Cookie.rst +++ b/zh/api/Phalcon_Http_Cookie.rst @@ -46,13 +46,15 @@ Returns the cookie's value public **send** () -Sends the cookie to the HTTP client Stores the cookie definition in session +Sends the cookie to the HTTP client +Stores the cookie definition in session public **restore** () -Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don't need to call it +Reads the cookie-related info from the SESSION to restore the cookie as it was set +This method is automatically called internally so normally you don't need to call it diff --git a/zh/api/Phalcon_Http_Request.rst b/zh/api/Phalcon_Http_Request.rst index 0fbd92d4c55e..99d05fa87515 100644 --- a/zh/api/Phalcon_Http_Request.rst +++ b/zh/api/Phalcon_Http_Request.rst @@ -8,25 +8,26 @@ Class **Phalcon\\Http\\Request** :raw-html:`Source on GitHub` -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. +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()) { - if ($request->isAjax()) { - echo 'Request was made using POST and AJAX'; - } - } - - $request->getServer('HTTP_HOST'); // retrieve SERVER variables - $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT - $request->getLanguages(); // an array of languages the client accepts + use Phalcon\Http\Request; + + $request = new Request(); + + if ($request->isPost() && $request->isAjax()) { + echo "Request was made using POST and AJAX"; + } + + $request->getServer("HTTP_HOST"); // Retrieve SERVER variables + $request->getMethod(); // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT + $request->getLanguages(); // An array of languages the client accepts @@ -57,16 +58,17 @@ Returns the internal dependency injector public **get** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned +Gets a variable from the $_REQUEST superglobal applying filters if needed. +If no parameters are given the $_REQUEST superglobal is returned .. code-block:: php get("user_email"); - - //Returns value from $_REQUEST["user_email"] with sanitizing + + // Returns value from $_REQUEST["user_email"] with sanitizing $userEmail = $request->get("user_email", "email"); @@ -74,16 +76,17 @@ Gets a variable from the $_REQUEST superglobal applying filters if needed. If no public **getPost** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned +Gets a variable from the $_POST superglobal applying filters if needed +If no parameters are given the $_POST superglobal is returned .. code-block:: php getPost("user_email"); - - //Returns value from $_POST["user_email"] with sanitizing + + // Returns value from $_POST["user_email"] with sanitizing $userEmail = $request->getPost("user_email", "email"); @@ -91,16 +94,16 @@ Gets a variable from the $_POST superglobal applying filters if needed If no par public **getPut** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets a variable from put request +Gets a variable from put request .. code-block:: php getPut("user_email"); - - //Returns value from $_PUT["user_email"] with sanitizing + + // Returns value from $_PUT["user_email"] with sanitizing $userEmail = $request->getPut("user_email", "email"); @@ -108,27 +111,29 @@ Gets a variable from put request public **getQuery** ([*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned +Gets variable from $_GET superglobal applying filters if needed +If no parameters are given the $_GET superglobal is returned .. code-block:: php getQuery('id'); - - // Returns value from $_GET['id'] with sanitizing - $id = $request->getQuery('id', 'int'); - - // Returns value from $_GET['id'] with a default value - $id = $request->getQuery('id', null, 150); + // Returns value from $_GET["id"] without sanitizing + $id = $request->getQuery("id"); + + // Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + // Returns value from $_GET["id"] with a default value + $id = $request->getQuery("id", null, 150); final protected **getHelper** (*array* $source, [*mixed* $name], [*mixed* $filters], [*mixed* $defaultValue], [*mixed* $notAllowEmpty], [*mixed* $noRecursive]) -Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned. +Helper to get data from superglobals, applying filters if needed. +If no parameters are given the superglobal is returned. @@ -236,28 +241,36 @@ Gets active server name public **getHttpHost** () -Gets host name used by the request. `Request::getHttpHost` trying to find host name in following order: - `$_SERVER['HTTP_HOST']` - `$_SERVER['SERVER_NAME']` - `$_SERVER['SERVER_ADDR']` Optionally `Request::getHttpHost` validates and clean host name. The `Request::$_strictHostCheck` can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions. +Gets host name used by the request. +`Request::getHttpHost` trying to find host name in following order: +- `$_SERVER["HTTP_HOST"]` +- `$_SERVER["SERVER_NAME"]` +- `$_SERVER["SERVER_ADDR"]` +Optionally `Request::getHttpHost` validates and clean host name. +The `Request::$_strictHostCheck` can be used to validate host name. +Note: validation and cleaning have a negative performance impact because +they use regular expressions. .. code-block:: php getHttpHost(); // example.com - - $_SERVER['HTTP_HOST'] = 'example.com:8080'; - $request->getHttpHost(); // example.com:8080 - - $request->setStrictHostCheck(true); - $_SERVER['HTTP_HOST'] = 'ex=am~ple.com'; - $request->getHttpHost(); // UnexpectedValueException - - $_SERVER['HTTP_HOST'] = 'ExAmPlE.com'; - $request->getHttpHost(); // example.com + use Phalcon\Http\Request; + + $request = new Request; + + $_SERVER["HTTP_HOST"] = "example.com"; + $request->getHttpHost(); // example.com + + $_SERVER["HTTP_HOST"] = "example.com:8080"; + $request->getHttpHost(); // example.com:8080 + + $request->setStrictHostCheck(true); + $_SERVER["HTTP_HOST"] = "ex=am~ple.com"; + $request->getHttpHost(); // UnexpectedValueException + + $_SERVER["HTTP_HOST"] = "ExAmPlE.com"; + $request->getHttpHost(); // example.com @@ -288,13 +301,19 @@ Gets HTTP URI which request has been made public **getClientAddress** ([*mixed* $trustForwardedHeader]) -Gets most possible client IPv4 Address. This method search in _SERVER['REMOTE_ADDR'] and optionally in _SERVER['HTTP_X_FORWARDED_FOR'] +Gets most possible client IPv4 Address. This method searches in +$_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] final public **getMethod** () -Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string. +Gets HTTP method which request has been made +If the X-HTTP-Method-Override header is set, and if the method is a POST, +then it is used to determine the "real" intended HTTP method. +The _method request parameter can also be used to determine the HTTP method, +but only if setHttpMethodParameterOverride(true) has been called. +The method is always an uppercased string. @@ -312,7 +331,8 @@ Checks if a method is a valid HTTP method public **isMethod** (*mixed* $methods, [*mixed* $strict]) -Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods +Check if HTTP method match any of the passed methods +When strict is true it checks if validated methods are real HTTP methods @@ -404,17 +424,25 @@ public **getHeaders** () Returns the available headers in the request +.. code-block:: php + + "phalcon", + "PHP_AUTH_PW" => "secret", + ]; -public **getHTTPReferer** () + $headers = $request->getHeaders(); -Gets web page that refers active request. ie: http://www.google.com + echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ= -final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) -Process a request header and return an array of values with their qualities +public **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com @@ -468,13 +496,19 @@ Gets best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANG public **getBasicAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_USER'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"] public **getDigestAuth** () -Gets auth info accepted by the browser/client from $_SERVER['PHP_AUTH_DIGEST'] +Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"] + + + +final protected **_getQualityHeader** (*mixed* $serverIndex, *mixed* $name) + +Process a request header and return an array of values with their qualities diff --git a/zh/api/Phalcon_Http_Request_File.rst b/zh/api/Phalcon_Http_Request_File.rst index 9471e496e754..af7c5dd92b17 100644 --- a/zh/api/Phalcon_Http_Request_File.rst +++ b/zh/api/Phalcon_Http_Request_File.rst @@ -8,27 +8,26 @@ Class **Phalcon\\Http\\Request\\File** :raw-html:`Source on GitHub` -Provides OO wrappers to the $_FILES superglobal +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"; - } + public function uploadAction() + { + // Check if the user has uploaded files + if ($this->request->hasFiles() == true) { + // Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } } - } } @@ -80,7 +79,8 @@ Returns the temporary name of the uploaded file public **getType** () -Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead +Returns the mime type reported by the browser +This mime type is not completely secure, use getRealType() instead diff --git a/zh/api/Phalcon_Http_Response.rst b/zh/api/Phalcon_Http_Response.rst index 42116fbdd141..bae2f22641c4 100644 --- a/zh/api/Phalcon_Http_Response.rst +++ b/zh/api/Phalcon_Http_Response.rst @@ -8,15 +8,19 @@ Class **Phalcon\\Http\\Response** :raw-html:`Source on GitHub` -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. +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(); @@ -44,7 +48,7 @@ Returns the internal dependency injector public **setStatusCode** (*mixed* $code, [*mixed* $message]) -Sets the HTTP response code +Sets the HTTP response code .. code-block:: php @@ -57,13 +61,15 @@ Sets the HTTP response code public **getStatusCode** () -Returns the status code +Returns the status code .. code-block:: php getStatusCode()); + print_r( + $response->getStatusCode() + ); @@ -88,13 +94,13 @@ Sets a cookies bag for the response externally public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () -Returns coookies set by the user +Returns cookies set by the user public **setHeader** (*mixed* $name, *mixed* $value) -Overwrites a header in the response +Overwrites a header in the response .. code-block:: php @@ -107,7 +113,7 @@ Overwrites a header in the response public **setRawHeader** (*mixed* $header) -Send a raw header to the response +Send a raw header to the response .. code-block:: php @@ -120,39 +126,43 @@ Send a raw header to the response public **resetHeaders** () -Resets all the stablished headers +Resets all the established headers public **setExpires** (`DateTime `_ $datetime) -Sets an Expires header in the response that allows to use the HTTP cache +Sets an Expires header in the response that allows to use the HTTP cache .. code-block:: php response->setExpires(new DateTime()); + $this->response->setExpires( + new DateTime() + ); public **setLastModified** (`DateTime `_ $datetime) -Sets Last-Modified header +Sets Last-Modified header .. code-block:: php response->setLastModified(new DateTime()); + $this->response->setLastModified( + new DateTime() + ); public **setCache** (*mixed* $minutes) -Sets Cache headers to use HTTP cache +Sets Cache headers to use HTTP cache .. code-block:: php @@ -171,21 +181,21 @@ Sends a Not-Modified response public **setContentType** (*mixed* $contentType, [*mixed* $charset]) -Sets the response content-type mime, optionally the charset +Sets the response content-type mime, optionally the charset .. code-block:: php setContentType('application/pdf'); - $response->setContentType('text/plain', 'UTF-8'); + $response->setContentType("application/pdf"); + $response->setContentType("text/plain", "UTF-8"); public **setContentLength** (*mixed* $contentLength) -Sets the response content-length +Sets the response content-length .. code-block:: php @@ -198,7 +208,7 @@ Sets the response content-length public **setEtag** (*mixed* $etag) -Set a custom ETag +Set a custom ETag .. code-block:: php @@ -211,49 +221,56 @@ Set a custom ETag public **redirect** ([*mixed* $location], [*mixed* $externalRedirect], [*mixed* $statusCode]) -Redirect by HTTP to another action or URL +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); - - //Making a redirection based on a named route - $response->redirect(array( - "for" => "index-lang", - "lang" => "jp", - "controller" => "index" - )); + + // Making a redirection based on a named route + $response->redirect( + [ + "for" => "index-lang", + "lang" => "jp", + "controller" => "index", + ] + ); public **setContent** (*mixed* $content) -Sets HTTP response body +Sets HTTP response body .. code-block:: php setContent("

Hello!

"); + $response->setContent("

Hello!

"); public **setJsonContent** (*mixed* $content, [*mixed* $jsonOptions], [*mixed* $depth]) -Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8" +Sets HTTP response body. The parameter is automatically converted to JSON +and also sets default header: Content-Type: "application/json; charset=UTF-8" .. code-block:: php setJsonContent(array("status" => "OK")); + $response->setJsonContent( + [ + "status" => "OK", + ] + ); diff --git a/zh/api/Phalcon_Http_Response_Cookies.rst b/zh/api/Phalcon_Http_Response_Cookies.rst index 5e99fe716d1b..61e0fb669187 100644 --- a/zh/api/Phalcon_Http_Response_Cookies.rst +++ b/zh/api/Phalcon_Http_Response_Cookies.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Http\\Response\\Cookies** :raw-html:`Source on GitHub` -This class is a bag to manage the cookies A cookies bag is automatically registered as part of the 'response' service in the DI +This class is a bag to manage the cookies +A cookies bag is automatically registered as part of the 'response' service in the DI Methods @@ -40,7 +41,8 @@ Returns if the bag is automatically encrypting/decrypting cookies public **set** (*mixed* $name, [*mixed* $value], [*mixed* $expire], [*mixed* $path], [*mixed* $secure], [*mixed* $domain], [*mixed* $httpOnly]) -Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name +Sets a cookie to be sent at the end of the request +This method overrides any cookie set before with the same name @@ -58,13 +60,15 @@ Check if a cookie is defined in the bag or exists in the _COOKIE superglobal public **delete** (*mixed* $name) -Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal +Deletes a cookie by its name +This method does not removes cookies from the _COOKIE superglobal public **send** () -Sends the cookies to the client Cookies aren't sent if headers are sent in the current request +Sends the cookies to the client +Cookies aren't sent if headers are sent in the current request diff --git a/zh/api/Phalcon_Image_Adapter.rst b/zh/api/Phalcon_Image_Adapter.rst index 9197c2d56be4..3024160aee58 100644 --- a/zh/api/Phalcon_Image_Adapter.rst +++ b/zh/api/Phalcon_Image_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Image\\Adapter** ========================================== +*implements* :doc:`Phalcon\\Image\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -36,7 +38,8 @@ Image height public **getType** () -Image type Driver dependent +Image type +Driver dependent diff --git a/zh/api/Phalcon_Image_Adapter_Gd.rst b/zh/api/Phalcon_Image_Adapter_Gd.rst index 7717005c106b..8ac3c8d3e728 100644 --- a/zh/api/Phalcon_Image_Adapter_Gd.rst +++ b/zh/api/Phalcon_Image_Adapter_Gd.rst @@ -127,7 +127,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/zh/api/Phalcon_Image_Adapter_Imagick.rst b/zh/api/Phalcon_Image_Adapter_Imagick.rst index 5d2998fa76d5..2dc90632148a 100644 --- a/zh/api/Phalcon_Image_Adapter_Imagick.rst +++ b/zh/api/Phalcon_Image_Adapter_Imagick.rst @@ -10,17 +10,19 @@ Class **Phalcon\\Image\\Adapter\\Imagick** :raw-html:`Source on GitHub` -Image manipulation support. Allows images to be resized, cropped, etc. +Image manipulation support. Allows images to be resized, cropped, etc. .. code-block:: php resize(200, 200)->rotate(90)->crop(100, 100); - if ($image->save()) { - echo 'success'; - } + $image = new \Phalcon\Image\Adapter\Imagick("upload/test.jpg"); + + $image->resize(200, 200)->rotate(90)->crop(100, 100); + + if ($image->save()) { + echo "success"; + } @@ -171,7 +173,8 @@ Image height public **getType** () inherited from :doc:`Phalcon\\Image\\Adapter ` -Image type Driver dependent +Image type +Driver dependent diff --git a/zh/api/Phalcon_Loader.rst b/zh/api/Phalcon_Loader.rst index 388c92a792ca..a9d9f2ce68b9 100644 --- a/zh/api/Phalcon_Loader.rst +++ b/zh/api/Phalcon_Loader.rst @@ -8,27 +8,31 @@ Class **Phalcon\\Loader** :raw-html:`Source on GitHub` -This component helps to load your project classes automatically based on some conventions +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 this class will automatically include file vendor/example/adapter/Some.php - $adapter = Example\Adapter\Some(); + use Phalcon\Loader; + + // Creates the autoloader + $loader = new Loader(); + + // Register some namespaces + $loader->registerNamespaces( + [ + "Example\\Base" => "vendor/example/base/", + "Example\\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ] + ); + + // Register autoloader + $loader->register(); + + // Requiring this class will automatically include file vendor/example/adapter/Some.php + $adapter = new \Example\Adapter\Some(); @@ -90,7 +94,8 @@ Returns the directories currently registered in the autoloader public **registerFiles** (*array* $files, [*mixed* $merge]) -Registers files that are "non-classes" hence need a "require". This is very useful for including files that only have functions +Registers files that are "non-classes" hence need a "require". This is very useful for including files that only +have functions diff --git a/zh/api/Phalcon_Logger_Adapter.rst b/zh/api/Phalcon_Logger_Adapter.rst index 3cd20074b154..d880ef15f9f0 100644 --- a/zh/api/Phalcon_Logger_Adapter.rst +++ b/zh/api/Phalcon_Logger_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Logger\\Adapter** =========================================== +*implements* :doc:`Phalcon\\Logger\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -108,3 +110,13 @@ Logs messages to the internal logger. Appends logs to the logger +abstract public **getFormatter** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + +abstract public **close** () inherited from :doc:`Phalcon\\Logger\\AdapterInterface ` + +... + + diff --git a/zh/api/Phalcon_Logger_Adapter_File.rst b/zh/api/Phalcon_Logger_Adapter_File.rst index bd6f112d4a54..a91ec1264fbb 100644 --- a/zh/api/Phalcon_Logger_Adapter_File.rst +++ b/zh/api/Phalcon_Logger_Adapter_File.rst @@ -10,16 +10,18 @@ Class **Phalcon\\Logger\\Adapter\\File** :raw-html:`Source on GitHub` -Adapter to store logs in plain text files +Adapter to store logs in plain text files .. code-block:: php log("This is a message"); $logger->log(\Phalcon\Logger::ERROR, "This is an error"); $logger->error("This is another error"); + $logger->close(); diff --git a/zh/api/Phalcon_Logger_Adapter_Firephp.rst b/zh/api/Phalcon_Logger_Adapter_Firephp.rst index 68af7e65c7ed..45725fb808e3 100644 --- a/zh/api/Phalcon_Logger_Adapter_Firephp.rst +++ b/zh/api/Phalcon_Logger_Adapter_Firephp.rst @@ -10,18 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Firephp** :raw-html:`Source on GitHub` -Sends logs to FirePHP +Sends logs to FirePHP .. code-block:: php log(Logger::ERROR, 'This is an error'); - $logger->error('This is another error'); + use Phalcon\Logger\Adapter\Firephp; + use Phalcon\Logger; + + $logger = new Firephp(); + + $logger->log(Logger::ERROR, "This is an error"); + $logger->error("This is another error"); diff --git a/zh/api/Phalcon_Logger_Adapter_Stream.rst b/zh/api/Phalcon_Logger_Adapter_Stream.rst index 6758985817b0..105deb7580b6 100644 --- a/zh/api/Phalcon_Logger_Adapter_Stream.rst +++ b/zh/api/Phalcon_Logger_Adapter_Stream.rst @@ -10,15 +10,19 @@ Class **Phalcon\\Logger\\Adapter\\Stream** :raw-html:`Source on GitHub` -Sends logs to a valid PHP stream +Sends logs to a valid PHP stream .. code-block:: php log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); diff --git a/zh/api/Phalcon_Logger_Adapter_Syslog.rst b/zh/api/Phalcon_Logger_Adapter_Syslog.rst index 485a960c22a2..e17a5c873d08 100644 --- a/zh/api/Phalcon_Logger_Adapter_Syslog.rst +++ b/zh/api/Phalcon_Logger_Adapter_Syslog.rst @@ -10,18 +10,26 @@ Class **Phalcon\\Logger\\Adapter\\Syslog** :raw-html:`Source on GitHub` -Sends logs to the system logger +Sends logs to the system logger .. code-block:: php LOG_NDELAY, - 'facility' => LOG_MAIL - )); + use Phalcon\Logger; + use Phalcon\Logger\Adapter\Syslog; + + // LOG_USER is the only valid log type under Windows operating systems + $logger = new Syslog( + "ident", + [ + "option" => LOG_CONS | LOG_NDELAY | LOG_PID, + "facility" => LOG_USER, + ] + ); + $logger->log("This is a message"); - $logger->log(\Phalcon\Logger::ERROR, "This is an error"); + $logger->log(Logger::ERROR, "This is an error"); $logger->error("This is another error"); @@ -41,7 +49,7 @@ Returns the internal formatter -public **logInternal** (*string* $message, *int* $type, *int* $time, *array* $context) +public **logInternal** (*mixed* $message, *mixed* $type, *mixed* $time, *array* $context) Writes the log to the stream itself diff --git a/zh/api/Phalcon_Mvc_Application.rst b/zh/api/Phalcon_Mvc_Application.rst index 65c41c2cdf41..27e0d8802c9c 100644 --- a/zh/api/Phalcon_Mvc_Application.rst +++ b/zh/api/Phalcon_Mvc_Application.rst @@ -10,45 +10,48 @@ Class **Phalcon\\Mvc\\Application** :raw-html:`Source on GitHub` -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. +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' - ) - )); - } + use Phalcon\Mvc\Application; + + class MyApp extends Application + { + /** + * Register the services here to make them general or register + * in the ModuleDefinition to make them module-specific + */ + protected function registerServices() + { + + } + + /** + * This method registers all the modules in the application + */ + public function main() + { + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); + } } - + $application = new MyApp(); + $application->main(); @@ -58,7 +61,8 @@ Methods public **useImplicitView** (*mixed* $implicitView) -By default. The view is implicitly buffering all the output You can full disable the view component using this method +By default. The view is implicitly buffering all the output +You can full disable the view component using this method @@ -88,24 +92,24 @@ Returns the internal event manager public **registerModules** (*array* $modules, [*mixed* $merge]) inherited from :doc:`Phalcon\\Application ` -Register an array of modules present in the application +Register an array of modules present in the application .. code-block:: php registerModules( - [ - 'frontend' => [ - 'className' => 'Multiple\Frontend\Module', - 'path' => '../apps/frontend/Module.php' - ], - 'backend' => [ - 'className' => 'Multiple\Backend\Module', - 'path' => '../apps/backend/Module.php' - ] - ] - ); + $this->registerModules( + [ + "frontend" => [ + "className" => "Multiple\\Frontend\\Module", + "path" => "../apps/frontend/Module.php", + ], + "backend" => [ + "className" => "Multiple\\Backend\\Module", + "path" => "../apps/backend/Module.php", + ], + ] + ); diff --git a/zh/api/Phalcon_Mvc_Collection.rst b/zh/api/Phalcon_Mvc_Collection.rst index c77a32b4fec6..475a7d7b371c 100644 --- a/zh/api/Phalcon_Mvc_Collection.rst +++ b/zh/api/Phalcon_Mvc_Collection.rst @@ -8,7 +8,8 @@ Abstract class **Phalcon\\Mvc\\Collection** :raw-html:`Source on GitHub` -This component implements a high level abstraction for NoSQL databases which works with documents +This component implements a high level abstraction for NoSQL databases which +works with documents Constants @@ -117,26 +118,26 @@ Retrieves a database connection public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); @@ -173,28 +174,31 @@ Executes internal events after save a document protected **validate** (:doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` $validator) -Executes validators on every validation call +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -202,28 +206,31 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +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 function validation() + { + $this->validate( + new ExclusionIn( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() == true) { + return false; + } + } } @@ -255,23 +262,28 @@ Checks if the document exists in the collection public **getMessages** () -Returns all the validation messages +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; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -279,24 +291,26 @@ Returns all the validation messages public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage(message); + } + } } @@ -304,7 +318,8 @@ Appends a customized message on the validation process protected **prepareCU** () -Shared Code for CU Operations Prepares Collection +Shared Code for CU Operations +Prepares Collection @@ -322,7 +337,26 @@ Creates a collection based on the values in the attributes public **createIfNotExist** (*array* $criteria) -Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = "MyRobot"; $robot->type = "Droid"; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( "name", "type" ) ); +Creates a document based on the values in the attributes, if not found by criteria +Preferred way to avoid duplication is to create index on attribute + +.. code-block:: php + + name = "MyRobot"; + $robot->type = "Droid"; + + // Create only if robot with same name and type does not exist + $robot->createIfNotExist( + [ + "name", + "type", + ] + ); + @@ -334,109 +368,149 @@ Creates/Updates a collection based on the values in the attributes public static **findById** (*mixed* $id) -Find a document by its id (_id) +Find a document by its id (_id) .. 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([ - ['type' => 'mechanical'], - 'order' => ['name' => 1] - ]); - echo 'The first virtual robot name is ', $robot->name, "\n"; - - // Get first robot by id (_id) - $robot = Robots::findFirst([ - ['_id' => new \MongoId('45cbc4a0e4123f6920000002')] - ]); - echo 'The robot id is ', $robot->_id, "\n"; + // What's the first robot in the robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + [ + "type" => "mechanical", + ], + "order" => [ + "name" => 1, + ], + ] + ); + + echo "The first virtual robot name is ", $robot->name, "\n"; + + // Get first robot by id (_id) + $robot = Robots::findFirst( + [ + [ + "_id" => new \MongoId("45cbc4a0e4123f6920000002"), + ] + ] + ); + + echo "The robot id is ", $robot->_id, "\n"; public static **find** ([*array* $parameters]) -Allows to query a set of records that match the specified conditions +Allows to query a set of records that match the specified conditions .. code-block:: php "mechanical") - )); - echo "There are ", count(robots), "\n"; - - //Get and print virtual robots ordered by name - $robots = Robots::findFirst(array( - array("type" => "virtual"), - "order" => array("name" => 1) - )); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + [ + [ + "type" => "mechanical", + ] + ] + ); + + echo "There are ", count(robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::findFirst( + [ + [ + "type" => "virtual" + ], + "order" => [ + "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) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + [ + "type" => "virtual", + ], + "order" => [ + "name" => 1, + ], + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static **count** ([*array* $parameters]) -Perform a count over a collection +Perform a count over a collection .. code-block:: php delete(); - - foreach (Robots::find() as $robot) { - $robot->delete(); + + $robots = Robots::find(); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -485,13 +562,15 @@ Skips the current operation forcing a success state public **toArray** () -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); diff --git a/zh/api/Phalcon_Mvc_Collection_Behavior.rst b/zh/api/Phalcon_Mvc_Collection_Behavior.rst index 3fc0a5633f95..00c01875c072 100644 --- a/zh/api/Phalcon_Mvc_Collection_Behavior.rst +++ b/zh/api/Phalcon_Mvc_Collection_Behavior.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Collection\\Behavior** ===================================================== +*implements* :doc:`Phalcon\\Mvc\\Collection\\BehaviorInterface ` + .. role:: raw-html(raw) :format: html diff --git a/zh/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst b/zh/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst index 4ad55f95d500..7af6d07d8e64 100644 --- a/zh/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst +++ b/zh/api/Phalcon_Mvc_Collection_Behavior_SoftDelete.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\SoftDelete** :raw-html:`Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/zh/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst b/zh/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst index 5f416aa5ff75..e8c08ca66d5a 100644 --- a/zh/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst +++ b/zh/api/Phalcon_Mvc_Collection_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Collection\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/zh/api/Phalcon_Mvc_Collection_Document.rst b/zh/api/Phalcon_Mvc_Collection_Document.rst index 1e93eba65321..a1c90050f4d1 100644 --- a/zh/api/Phalcon_Mvc_Collection_Document.rst +++ b/zh/api/Phalcon_Mvc_Collection_Document.rst @@ -8,7 +8,8 @@ Class **Phalcon\\Mvc\\Collection\\Document** :raw-html:`Source on GitHub` -This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Collection to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -40,26 +41,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/zh/api/Phalcon_Mvc_Collection_Manager.rst b/zh/api/Phalcon_Mvc_Collection_Manager.rst index 9196796f5dee..fb389960fee3 100644 --- a/zh/api/Phalcon_Mvc_Collection_Manager.rst +++ b/zh/api/Phalcon_Mvc_Collection_Manager.rst @@ -8,19 +8,25 @@ Class **Phalcon\\Mvc\\Collection\\Manager** :raw-html:`Source on GitHub` -This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. +This components controls the initialization of models, keeping record of relations +between the different models of the application. + +A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\\Di. .. code-block:: php set('collectionManager', function(){ - return new \Phalcon\Mvc\Collection\Manager(); - }); - - $robot = new Robots($di); + $di = new \Phalcon\Di(); + + $di->set( + "collectionManager", + function () { + return new \Phalcon\Mvc\Collection\Manager(); + } + ); + + $robot = new Robots($di); @@ -123,13 +129,16 @@ Returns the connection related to a model public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\CollectionInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\CollectionInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that at least one was implemented diff --git a/zh/api/Phalcon_Mvc_Controller.rst b/zh/api/Phalcon_Mvc_Controller.rst index 4363bc6e161a..2e31504978e3 100644 --- a/zh/api/Phalcon_Mvc_Controller.rst +++ b/zh/api/Phalcon_Mvc_Controller.rst @@ -10,34 +10,41 @@ Abstract class **Phalcon\\Mvc\\Controller** :raw-html:`Source on GitHub` -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. +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 by default + public function indexAction() + { + + } + + public function findAction() + { + + } + + public function saveAction() + { + // Forwards flow to the index action + return $this->dispatcher->forward( + [ + "controller" => "people", + "action" => "index", + ] + ); + } } diff --git a/zh/api/Phalcon_Mvc_Dispatcher.rst b/zh/api/Phalcon_Mvc_Dispatcher.rst index da3ec08bb4e1..fab5047b7b69 100644 --- a/zh/api/Phalcon_Mvc_Dispatcher.rst +++ b/zh/api/Phalcon_Mvc_Dispatcher.rst @@ -10,22 +10,24 @@ Class **Phalcon\\Mvc\\Dispatcher** :raw-html:`Source on GitHub` -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. +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()); - + + $dispatcher->setDI($di); + + $dispatcher->setControllerName("posts"); + $dispatcher->setActionName("index"); + $dispatcher->setParams([]); + $controller = $dispatcher->dispatch(); @@ -284,13 +286,19 @@ Dispatches a handle action taking into account the routing parameters public **forward** (*array* $forward) inherited from :doc:`Phalcon\\Dispatcher ` -Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed +Forwards the execution flow to another controller/action +Dispatchers are unique per module. Forwarding between modules is not allowed .. code-block:: php dispatcher->forward(array("controller" => "posts", "action" => "index")); + $this->dispatcher->forward( + [ + "controller" => "posts", + "action" => "index", + ] + ); diff --git a/zh/api/Phalcon_Mvc_Micro.rst b/zh/api/Phalcon_Mvc_Micro.rst index 6c75142f532d..87d9c8b5353b 100644 --- a/zh/api/Phalcon_Mvc_Micro.rst +++ b/zh/api/Phalcon_Mvc_Micro.rst @@ -10,19 +10,24 @@ Class **Phalcon\\Mvc\\Micro** :raw-html:`Source on GitHub` -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. +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(); + $app = new \Phalcon\Mvc\Micro(); + + $app->get( + "/say/welcome/{name}", + function ($name) { + echo "

Welcome $name!

"; + } + ); + + $app->handle(); @@ -175,26 +180,28 @@ Check if a service is registered in the internal services container using the ar public **offsetSet** (*string* $alias, *mixed* $definition) -Allows to register a shared service in the internal services container using the array syntax +Allows to register a shared service in the internal services container using the array syntax .. code-block:: php Source on GitHub` -Groups Micro-Mvc handlers as controllers +Groups Micro-Mvc handlers as controllers .. code-block:: php setHandler(new PostsController()); - - $collection->get('/posts/edit/{id}', 'edit'); - - $app->mount($collection); + $app = new \Phalcon\Mvc\Micro(); + + $collection = new Collection(); + + $collection->setHandler( + new PostsController() + ); + + $collection->get("/posts/edit/{id}", "edit"); + + $app->mount($collection); diff --git a/zh/api/Phalcon_Mvc_Model.rst b/zh/api/Phalcon_Mvc_Model.rst index c82921726ad7..9285fb35e44d 100644 --- a/zh/api/Phalcon_Mvc_Model.rst +++ b/zh/api/Phalcon_Mvc_Model.rst @@ -8,24 +8,39 @@ Abstract class **Phalcon\\Mvc\\Model** :raw-html:`Source on GitHub` -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 Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use. +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 Zephir/C languages 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!"; - } + $robot = new Robots(); + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + if ($robot->save() === false) { + echo "Umh, We can store robots: "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } @@ -93,7 +108,7 @@ Returns the models manager related to the entity instance public **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\TransactionInterface ` $transaction) -Sets a transaction related to the Model instance +Sets a transaction related to the Model instance .. code-block:: php @@ -101,32 +116,36 @@ Sets a transaction related to the Model instance use Phalcon\Mvc\Model\Transaction\Manager as TxManager; use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; - + try { - - $txManager = new TxManager(); - - $transaction = $txManager->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("Robot part cannot be saved"); - } - - $transaction->commit(); - + $txManager = new TxManager(); + + $transaction = $txManager->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("Robot part cannot be saved"); + } + + $transaction->commit(); } catch (TxFailed $e) { - echo 'Failed, reason: ', $e->getMessage(); + echo "Failed, reason: ", $e->getMessage(); } @@ -134,25 +153,25 @@ Sets a transaction related to the Model instance protected **setSource** (*mixed* $source) -Sets table name which model should be mapped +Sets the table name to which model should be mapped public **getSource** () -Returns table name mapped in the model +Returns the table name mapped in the model protected **setSchema** (*mixed* $schema) -Sets schema name where table mapped is located +Sets schema name where the mapped table is located public **getSchema** () -Returns schema name where table mapped is located +Returns schema name where the mapped table is located @@ -212,44 +231,59 @@ Gets the connection used to write data to the model public :doc:`Phalcon\\Mvc\\Model ` **assign** (*array* $data, [*mixed* $dataColumnMap], [*array* $whiteList]) -Assigns values to a model from an array +Assigns values to a model from an array .. code-block:: php assign(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); - - //assign by db row, column map needed - $robot->assign($dbRow, array( - 'db_type' => 'type', - 'db_name' => 'name', - 'db_year' => 'year' - )); - - //allow assign only name and year - $robot->assign($_POST, null, array('name', 'year'); + $robot->assign( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); + + // Assign by db row, column map needed + $robot->assign( + $dbRow, + [ + "db_type" => "type", + "db_name" => "name", + "db_year" => "year", + ] + ); + + // Allow assign only name and year + $robot->assign( + $_POST, + null, + [ + "name", + "year", + ] + ); public static **cloneResultMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` | :doc:`Phalcon\\Mvc\\Model\\Row ` $base, *array* $data, *array* $columnMap, [*int* $dirtyState], [*boolean* $keepSnapshots]) -Assigns values to a model from an array returning a new model. +Assigns values to a model from an array, returning a new model. .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = \Phalcon\Mvc\Model::cloneResultMap( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); @@ -262,71 +296,101 @@ Returns an hydrated result based on the data and the column map public static :doc:`Phalcon\\Mvc\\ModelInterface ` **cloneResult** (:doc:`Phalcon\\Mvc\\ModelInterface ` $base, *array* $data, [*int* $dirtyState]) -Assigns values to a model from an array returning a new model +Assigns values to a model from an array returning a new model .. code-block:: php 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + $robot = Phalcon\Mvc\Model::cloneResult( + new Robots(), + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public static **find** ([*mixed* $parameters]) -Allows to query a set of records that match the specified conditions +Query for a set of records that match the specified conditions .. code-block:: php 'name']); - foreach ($robots as $robot) { + // How many robots are there? + $robots = Robots::find(); + + echo "There are ", count($robots), "\n"; + + // How many mechanical robots are there? + $robots = Robots::find( + "type = 'mechanical'" + ); + + echo "There are ", count($robots), "\n"; + + // Get and print virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } - - // Get first 100 virtual robots ordered by name - $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]); - foreach ($robots as $robot) { + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + "limit" => 100, + ] + ); + + foreach ($robots as $robot) { echo $robot->name, "\n"; - } + } public static *static* **findFirst** ([*string* | *array* $parameters]) -Allows to query the first record that match the specified conditions +Query the first record that matches 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; + // What's the first robot in robots table? + $robot = Robots::findFirst(); + + echo "The robot name is ", $robot->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( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + echo "The first virtual robot name is ", $robot->name; @@ -339,7 +403,7 @@ Create a criteria for a specific model protected *boolean* **_exists** (:doc:`Phalcon\\Mvc\\Model\\MetaDataInterface ` $metaData, :doc:`Phalcon\\Db\\AdapterInterface ` $connection, [*string* | *array* $table]) -Checks if the current record already exists or not +Checks whether the current record already exists @@ -351,95 +415,141 @@ Generate a PHQL SELECT statement for an aggregate public static *mixed* **count** ([*array* $parameters]) -Allows to count how many records match the specified conditions +Counts how many records match the specified conditions .. code-block:: php 'price')); - echo "The total price of robots is ", $sum, "\n"; - - //How much are mechanical robots? - $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price')); - echo "The total price of mechanical robots is ", $sum, "\n"; + // How much are all robots? + $sum = Robots::sum( + [ + "column" => "price", + ] + ); + + echo "The total price of robots is ", $sum, "\n"; + + // How much are mechanical robots? + $sum = Robots::sum( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The total price of mechanical robots is ", $sum, "\n"; public static *mixed* **maximum** ([*array* $parameters]) -Allows to get the maximum value of a column that match the specified conditions +Returns the maximum value of a column for a result-set of rows that match the specified conditions .. code-block:: php 'id')); - echo "The maximum robot id is: ", $id, "\n"; - - //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, "\n"; + // What is the maximum robot id? + $id = Robots::maximum( + [ + "column" => "id", + ] + ); + + echo "The maximum robot id is: ", $id, "\n"; + + // What is the maximum id of mechanical robots? + $sum = Robots::maximum( + [ + "type = 'mechanical'", + "column" => "id", + ] + ); + + echo "The maximum robot id of mechanical robots is ", $id, "\n"; public static *mixed* **minimum** ([*array* $parameters]) -Allows to get the minimum value of a column that match the specified conditions +Returns the minimum value of a column for a result-set of rows 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; + // What is the minimum robot id? + $id = Robots::minimum( + [ + "column" => "id", + ] + ); + + echo "The minimum robot id is: ", $id; + + // What is the minimum id of mechanical robots? + $sum = Robots::minimum( + [ + "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 +Returns the average value on a column for a result-set of rows matching the specified conditions .. code-block:: php 'price')); - echo "The average price is ", $average, "\n"; - - //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, "\n"; + // What's the average price of robots? + $average = Robots::average( + [ + "column" => "price", + ] + ); + + echo "The average price is ", $average, "\n"; + + // What's the average price of mechanical robots? + $average = Robots::average( + [ + "type = 'mechanical'", + "column" => "price", + ] + ); + + echo "The average price of mechanical robots is ", $average, "\n"; @@ -452,7 +562,8 @@ Fires an event, implicitly calls behaviors and listeners in the events manager a public **fireEventCancel** (*mixed* $eventName) -Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false +Fires an event, implicitly calls behaviors and listeners in the events manager are notified +This method stops if one of the callbacks/listeners returns boolean false @@ -464,33 +575,35 @@ Cancel the current operation public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\MessageInterface ` $message) -Appends a customized message on the validation process +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); - } - } - } + use Phalcon\Mvc\Model; + use Phalcon\Mvc\Model\Message as Message; + + class Robots extends Model + { + public function beforeSave() + { + if ($this->name === "Peter") { + $message = new Message( + "Sorry, but a robot cannot be named Peter" + ); + + $this->appendMessage($message); + } + } + } protected **validate** (:doc:`Phalcon\\ValidationInterface ` $validator) -Executes validators on every validation call +Executes validators on every validation call .. code-block:: php @@ -499,19 +612,27 @@ Executes validators on every validation call use Phalcon\Mvc\Model; use Phalcon\Validation; use Phalcon\Validation\Validator\ExclusionIn; - + class Subscriptors extends Model { - - public function validation() - { - $validator = new Validation(); - $validator->add('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - ))); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->add( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -519,28 +640,36 @@ Executes validators on every validation call public **validationHasFailed** () -Check whether validation process has generated any messages +Check whether validation process has generated any messages .. code-block:: php validate('status', new ExclusionIn(array( - 'domain' => array('A', 'I') - )); - - return $this->validate($validator); - } + public function validation() + { + $validator = new Validation(); + + $validator->validate( + "status", + new ExclusionIn( + [ + "domain" => [ + "A", + "I", + ], + ] + ) + ); + + return $this->validate($validator); + } } @@ -548,23 +677,28 @@ Check whether validation process has generated any messages public **getMessages** ([*mixed* $filter]) -Returns array of validation messages +Returns array of validation messages .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->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; - } + + if ($robot->save() === false) { + echo "Umh, We can't store robots right now "; + + $messages = $robot->getMessages(); + + foreach ($messages as $message) { + echo $message; + } } else { - echo "Great, a new robot was saved successfully!"; + echo "Great, a new robot was saved successfully!"; } @@ -572,7 +706,8 @@ Returns array of validation messages final protected **_checkForeignKeysRestrict** () -Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records +to verify that inserted/updated values are present in the related entity @@ -626,22 +761,26 @@ Save the related records assigned in the has-one/has-many relations public *boolean* **save** ([*array* $data], [*array* $whiteList]) -Inserts or updates a model instance. Returning true on success or false otherwise. +Inserts or updates a model instance. Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->save(); - - //Updating a robot name - $robot = Robots::findFirst("id=100"); + + // Updating a robot name + $robot = Robots::findFirst("id = 100"); + $robot->name = "Biomass"; + $robot->save(); @@ -649,41 +788,50 @@ Inserts or updates a model instance. Returning true on success or false otherwis public **create** ([*mixed* $data], [*mixed* $whiteList]) -Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise. +Inserts a model instance. If the instance already exists in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php type = 'mechanical'; - $robot->name = 'Astro Boy'; + + $robot->type = "mechanical"; + $robot->name = "Astro Boy"; $robot->year = 1952; + $robot->create(); - - //Passing an array to create - $robot = new Robots(); - $robot->create(array( - 'type' => 'mechanical', - 'name' => 'Astro Boy', - 'year' => 1952 - )); + + // Passing an array to create + $robot = new Robots(); + + $robot->create( + [ + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952, + ] + ); public **update** ([*mixed* $data], [*mixed* $whiteList]) -Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception +Returning true on success or false otherwise. .. code-block:: php name = "Biomass"; + $robot->update(); @@ -691,17 +839,20 @@ Updates a model instance. If the instance doesn't exist in the persistence it wi public **delete** () -Deletes a model instance. Returning true on success or false otherwise. +Deletes a model instance. Returning true on success or false otherwise. .. code-block:: php delete(); - - foreach (Robots::find("type = 'mechanical'") as $robot) { - $robot->delete(); + + $robots = Robots::find("type = 'mechanical'"); + + foreach ($robots as $robot) { + $robot->delete(); } @@ -709,7 +860,8 @@ Deletes a model instance. Returning true on success or false otherwise. public **getOperationMade** () -Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants +Returns the type of the latest operation performed by the ORM +Returns one of the OP_* class constants @@ -727,47 +879,51 @@ Skips the current operation forcing a success state public **readAttribute** (*mixed* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*mixed* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); protected **skipAttributes** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement +Sets a list of attributes that must be skipped from the +generated INSERT/UPDATE statement .. code-block:: php skipAttributes(array('price')); - } + public function initialize() + { + $this->skipAttributes( + [ + "price", + ] + ); + } } @@ -775,21 +931,25 @@ Sets a list of attributes that must be skipped from the generated INSERT/UPDATE protected **skipAttributesOnCreate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated INSERT statement +Sets a list of attributes that must be skipped from the +generated INSERT statement .. code-block:: php skipAttributesOnCreate(array('created_at')); - } + public function initialize() + { + $this->skipAttributesOnCreate( + [ + "created_at", + ] + ); + } } @@ -797,21 +957,25 @@ Sets a list of attributes that must be skipped from the generated INSERT stateme protected **skipAttributesOnUpdate** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php skipAttributesOnUpdate(array('modified_in')); - } + public function initialize() + { + $this->skipAttributesOnUpdate( + [ + "modified_in", + ] + ); + } } @@ -819,21 +983,25 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **allowEmptyStringValues** (*array* $attributes) -Sets a list of attributes that must be skipped from the generated UPDATE statement +Sets a list of attributes that must be skipped from the +generated UPDATE statement .. code-block:: php allowEmptyStringValues(array('name')); - } + public function initialize() + { + $this->allowEmptyStringValues( + [ + "name", + ] + ); + } } @@ -841,21 +1009,20 @@ Sets a list of attributes that must be skipped from the generated UPDATE stateme protected **hasOne** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a 1-1 relation between two models +Setup a 1-1 relation between two models .. code-block:: php hasOne('id', 'RobotsDescription', 'robots_id'); - } + public function initialize() + { + $this->hasOne("id", "RobotsDescription", "robots_id"); + } } @@ -863,22 +1030,20 @@ Setup a 1-1 relation between two models protected **belongsTo** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation reverse 1-1 between two models +Setup a reverse 1-1 or n-1 relation between two models .. code-block:: php belongsTo('robots_id', 'Robots', 'id'); - } - + public function initialize() + { + $this->belongsTo("robots_id", "Robots", "id"); + } } @@ -886,21 +1051,20 @@ Setup a relation reverse 1-1 between two models protected **hasMany** (*mixed* $fields, *mixed* $referenceModel, *mixed* $referencedFields, [*mixed* $options]) -Setup a relation 1-n between two models +Setup a 1-n relation between two models .. code-block:: php hasMany('id', 'RobotsParts', 'robots_id'); - } + public function initialize() + { + $this->hasMany("id", "RobotsParts", "robots_id"); + } } @@ -908,29 +1072,28 @@ Setup a relation 1-n between two models protected :doc:`Phalcon\\Mvc\\Model\\Relation ` **hasManyToMany** (*string* | *array* $fields, *string* $intermediateModel, *string* | *array* $intermediateFields, *string* | *array* $intermediateReferencedFields, *mixed* $referenceModel, *string* | *array* $referencedFields, [*array* $options]) -Setup a relation n-n between two models through an intermediate relation +Setup an n-n relation between two models, through an intermediate relation .. code-block:: php hasManyToMany( - 'id', - 'RobotsParts', - 'robots_id', - 'parts_id', - 'Parts', - 'id' - ); - } + public function initialize() + { + // Setup a many-to-many relation to Parts through RobotsParts + $this->hasManyToMany( + "id", + "RobotsParts", + "robots_id", + "parts_id", + "Parts", + "id", + ); + } } @@ -938,29 +1101,32 @@ Setup a relation n-n between two models through an intermediate relation public **addBehavior** (:doc:`Phalcon\\Mvc\\Model\\BehaviorInterface ` $behavior) -Setups a behavior in a model +Setups a behavior in a model .. code-block:: php addBehavior(new Timestampable(array( - 'onCreate' => array( - 'field' => 'created_at', - 'format' => 'Y-m-d' - ) - ))); - } + public function initialize() + { + $this->addBehavior( + new Timestampable( + [ + "onCreate" => [ + "field" => "created_at", + "format" => "Y-m-d", + ], + ] + ) + ); + } } @@ -968,22 +1134,22 @@ Setups a behavior in a model protected **keepSnapshots** (*mixed* $keepSnapshot) -Sets if the model must keep the original record snapshot in memory +Sets if the model must keep the original record snapshot in memory .. code-block:: php keepSnapshots(true); - } + public function initialize() + { + $this->keepSnapshots(true); + } } @@ -991,7 +1157,8 @@ Sets if the model must keep the original record snapshot in memory public **setSnapshotData** (*array* $data, [*array* $columnMap]) -Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data +Sets the record's snapshot data. +This method is used internally to set snapshot data when the model was set up to keep snapshot data @@ -1009,7 +1176,8 @@ Returns the internal snapshot data public **hasChanged** ([*string* | *array* $fieldName]) -Check if a specific attribute has changed This only works if the model is keeping data snapshots +Check if a specific attribute has changed +This only works if the model is keeping data snapshots @@ -1021,22 +1189,22 @@ Returns a list of changed values protected **useDynamicUpdate** (*mixed* $dynamicUpdate) -Sets if a model must use dynamic update instead of the all-field update +Sets if a model must use dynamic update instead of the all-field update .. code-block:: php useDynamicUpdate(true); - } + public function initialize() + { + $this->useDynamicUpdate(true); + } } @@ -1110,39 +1278,43 @@ Unserializes the object from a serialized string public **dump** () -Returns a simple representation of the object that can be used with var_dump +Returns a simple representation of the object that can be used with var_dump .. code-block:: php dump()); + var_dump( + $robot->dump() + ); public *array* **toArray** ([*array* $columns]) -Returns the instance as an array representation +Returns the instance as an array representation .. code-block:: php toArray()); + print_r( + $robot->toArray() + ); public *array* **jsonSerialize** () -Serializes the object for json_encode +Serializes the object for json_encode .. code-block:: php Source on GitHub` -Instead of permanently delete a record it marks the record as deleted changing the value of a flag column +Instead of permanently delete a record it marks the record as +deleted changing the value of a flag column Methods diff --git a/zh/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst b/zh/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst index 6b68afcd7945..387a08ab9035 100644 --- a/zh/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst +++ b/zh/api/Phalcon_Mvc_Model_Behavior_Timestampable.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\Behavior\\Timestampable** :raw-html:`Source on GitHub` -Allows to automatically update a model’s attribute saving the datetime when a record is created or updated +Allows to automatically update a model’s attribute saving the +datetime when a record is created or updated Methods diff --git a/zh/api/Phalcon_Mvc_Model_Criteria.rst b/zh/api/Phalcon_Mvc_Model_Criteria.rst index 468b7565742c..8f612529051f 100644 --- a/zh/api/Phalcon_Mvc_Model_Criteria.rst +++ b/zh/api/Phalcon_Mvc_Model_Criteria.rst @@ -8,19 +8,21 @@ Class **Phalcon\\Mvc\\Model\\Criteria** :raw-html:`Source on GitHub` -This class is used to build the array parameter required by Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() using an object-oriented interface. +This class is used to build the array parameter required by +Phalcon\\Mvc\\Model::find() and Phalcon\\Mvc\\Model::findFirst() +using an object-oriented interface. .. code-block:: php where('type = :type:') - ->andWhere('year < 2000') - ->bind(['type' => 'mechanical']) - ->limit(5, 10) - ->orderBy('name') - ->execute(); + $robots = Robots::query() + ->where("type = :type:") + ->andWhere("year < 2000") + ->bind(["type" => "mechanical"]) + ->limit(5, 10) + ->orderBy("name") + ->execute(); @@ -53,13 +55,15 @@ Returns an internal model name on which the criteria will be applied public **bind** (*array* $bindParams, [*mixed* $merge]) -Sets the bound parameters in the criteria This method replaces all previously set bound parameters +Sets the bound parameters in the criteria +This method replaces all previously set bound parameters public **bindTypes** (*array* $bindTypes) -Sets the bind types in the criteria This method replaces all previously set bound parameters +Sets the bind types in the criteria +This method replaces all previously set bound parameters @@ -71,70 +75,75 @@ Sets SELECT DISTINCT / SELECT ALL flag public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **columns** (*string* | *array* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns(array('id', 'name')); + $criteria->columns( + [ + "id", + "name", + ] + ); public **join** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias], [*mixed* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - $criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + $criteria->join("Robots"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r"); + $criteria->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public **innerJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id'); - $criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->innerJoin("Robots"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id"); + $criteria->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **leftJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public **rightJoin** (*mixed* $model, [*mixed* $conditions], [*mixed* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $criteria->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -165,52 +174,52 @@ Appends a condition to the current conditions using an OR operator public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $criteria->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $criteria->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $criteria->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $criteria->notInWhere("id", [1, 2, 3]); @@ -247,7 +256,16 @@ Adds the having clause to the criteria public **limit** (*mixed* $limit, [*mixed* $offset]) -Adds the limit parameter to the criteria +Adds the limit parameter to the criteria. + +.. code-block:: php + + limit(100); + $criteria->limit(100, 200); + $criteria->limit("100", "200"); + @@ -265,7 +283,8 @@ Adds the "shared_lock" parameter to the criteria public **cache** (*array* $cache) -Sets the cache options in the criteria This method replaces all previously set cache options +Sets the cache options in the criteria +This method replaces all previously set cache options @@ -289,7 +308,10 @@ Returns the conditions parameter in the criteria public *int* | *array* | *null* **getLimit** () -Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with 'number' and 'offset' keys if an offset was set with the limit, or null if limit has not been set. +Returns the limit parameter in the criteria, which will be +an integer if limit was set without an offset, +an array with 'number' and 'offset' keys if an offset was set with the limit, +or null if limit has not been set. diff --git a/zh/api/Phalcon_Mvc_Model_Manager.rst b/zh/api/Phalcon_Mvc_Model_Manager.rst index 4593a3ab13b2..a9f7a132a5fc 100644 --- a/zh/api/Phalcon_Mvc_Model_Manager.rst +++ b/zh/api/Phalcon_Mvc_Model_Manager.rst @@ -8,22 +8,28 @@ Class **Phalcon\\Mvc\\Model\\Manager** :raw-html:`Source on GitHub` -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/Services Container such as Phalcon\\Di. +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/Services Container such as Phalcon\\Di. .. code-block:: php set('modelsManager', function() { - return new ModelsManager(); - }); - - $robot = new Robots($di); + use Phalcon\Di; + use Phalcon\Mvc\Model\Manager as ModelsManager; + + $di = new Di(); + + $di->set( + "modelsManager", + function() { + return new ModelsManager(); + } + ); + + $robot = new Robots($di); @@ -98,13 +104,16 @@ Sets the mapped source for a model final public **isVisibleModelProperty** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $property) -Check whether a model property is declared as public. +Check whether a model property is declared as public. .. code-block:: php isVisibleModelProperty(new Robots(), 'name'); + $isPublic = $manager->isVisibleModelProperty( + new Robots(), + "name" + ); @@ -177,19 +186,23 @@ Returns the connection service name used to write data related to a model public **_getConnectionService** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $connectionServices) -Returns the connection service name used to read or write data related to a model depending on the connection services +Returns the connection service name used to read or write data related to +a model depending on the connection services public **notifyEvent** (*mixed* $eventName, :doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model +Receives events generated in the models and dispatches them to an events-manager if available +Notify the behaviors that are listening in the model public **missingMethod** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $eventName, *mixed* $data) -Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented +Dispatch an event to the listeners and behaviors +This method expects that the endpoint listeners/behaviors returns true +meaning that a least one was implemented @@ -327,13 +340,15 @@ Gets belongsTo related records from a model public **getBelongsTo** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Gets all the belongsTo relations defined in a model +Gets all the belongsTo relations defined in a model .. code-block:: php getBelongsTo(new Robots()); + $relations = $modelsManager->getBelongsTo( + new Robots() + ); diff --git a/zh/api/Phalcon_Mvc_Model_Message.rst b/zh/api/Phalcon_Mvc_Model_Message.rst index 2ed537714e40..aa3dc886b675 100644 --- a/zh/api/Phalcon_Mvc_Model_Message.rst +++ b/zh/api/Phalcon_Mvc_Model_Message.rst @@ -8,29 +8,29 @@ Class **Phalcon\\Mvc\\Model\\Message** :raw-html:`Source on GitHub` -Encapsulates validation info generated before save/delete records fails +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); - } - } - - } + if ($this->name === "Peter") { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + + $message = new Message($text, $field, $type); + + $this->appendMessage($message); + } + } + } diff --git a/zh/api/Phalcon_Mvc_Model_MetaData.rst b/zh/api/Phalcon_Mvc_Model_MetaData.rst index f34165ccd781..198d9de5f1e8 100644 --- a/zh/api/Phalcon_Mvc_Model_MetaData.rst +++ b/zh/api/Phalcon_Mvc_Model_MetaData.rst @@ -8,14 +8,22 @@ Abstract class **Phalcon\\Mvc\\Model\\MetaData** :raw-html:`Source on GitHub` -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\\Mvc\\Model. 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: +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\\Mvc\\Model. +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()); + + $attributes = $metaData->getAttributes( + new Robots() + ); + print_r($attributes); @@ -90,319 +98,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Apc.rst index b07912c9b4da..27e3aba37822 100644 --- a/zh/api/Phalcon_Mvc_Model_MetaData_Apc.rst +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** :raw-html:`Source on GitHub` -Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') +Stores model meta-data in the APC cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Apc( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Files.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Files.rst index 843a3a466a88..e6572fd279d4 100644 --- a/zh/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -10,15 +10,17 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Files** :raw-html:`Source on GitHub` -Stores model meta-data in PHP files. +Stores model meta-data in PHP files. .. code-block:: php 'app/cache/metadata/' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Files( + [ + "metaDataDir" => "app/cache/metadata/", + ] + ); @@ -110,319 +112,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst index b3a5aa0342fe..c4343a9abe89 100644 --- a/zh/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Libmemcached.rst @@ -10,23 +10,31 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Libmemcached** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php array( - array('host' => 'localhost', 'port' => 11211, 'weight' => 1), - ), - 'client' => array( - Memcached::OPT_HASH => Memcached::HASH_MD5, - Memcached::OPT_PREFIX_KEY => 'prefix.', - ), - 'lifetime' => 3600, - 'prefix' => 'my_' - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + Memcached::OPT_HASH => Memcached::HASH_MD5, + Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); @@ -124,312 +132,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Memcache.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Memcache.rst index 6f1759ef9cce..175b08919ddb 100644 --- a/zh/api/Phalcon_Mvc_Model_MetaData_Memcache.rst +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Memcache.rst @@ -10,19 +10,23 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Memcache** :raw-html:`Source on GitHub` -Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Memcache. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php 'my-app-id', - 'lifetime' => 86400, - 'host' => 'localhost', - 'port' => 11211, - 'persistent' => false - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Memcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + "host" => "localhost", + "port" => 11211, + "persistent" => false, + ] + ); @@ -120,312 +124,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Memory.rst index 4c7a80146a4b..7bf4ecaebc30 100644 --- a/zh/api/Phalcon_Mvc_Model_MetaData_Memory.rst +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -101,319 +101,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Redis.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Redis.rst index 4bb94d685e3e..bf76b689514b 100644 --- a/zh/api/Phalcon_Mvc_Model_MetaData_Redis.rst +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Redis.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Redis** :raw-html:`Source on GitHub` -Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds) +Stores model meta-data in the Redis. + +By default meta-data is stored for 48 hours (172800 seconds) .. code-block:: php '127.0.0.1', - 'port' => 6379, - 'persistent' => 0, - 'statsKey' => '_PHCM_MM', - 'lifetime' => 172800, - 'index' => 2, - ]); + use Phalcon\Mvc\Model\Metadata\Redis; + + $metaData = new Redis( + [ + "host" => "127.0.0.1", + "port" => 6379, + "persistent" => 0, + "statsKey" => "_PHCM_MM", + "lifetime" => 172800, + "index" => 2, + ] + ); @@ -123,312 +127,416 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Session.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Session.rst index 8f23f2bf7a9b..0d1cbc9221a7 100644 --- a/zh/api/Phalcon_Mvc_Model_MetaData_Session.rst +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -10,15 +10,20 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Session** :raw-html:`Source on GitHub` -Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] +Stores model meta-data in session. Data will erased 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' - )); + $metaData = new \Phalcon\Mvc\Model\Metadata\Session( + [ + "prefix" => "my-app-id", + ] + ); @@ -110,319 +115,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Xcache.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Xcache.rst index a381923be613..d68c83709d38 100644 --- a/zh/api/Phalcon_Mvc_Model_MetaData_Xcache.rst +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Xcache.rst @@ -10,16 +10,22 @@ Class **Phalcon\\Mvc\\Model\\MetaData\\Xcache** :raw-html:`Source on GitHub` -Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') +Stores model meta-data in the XCache cache. Data will erased if the web server is restarted + +By default meta-data is stored for 48 hours (172800 seconds) + +You can query the meta-data by printing xcache_get('$PMM$') or xcache_get('$PMM$my-app-id') .. code-block:: php 'my-app-id', - 'lifetime' => 86400 - )); + $metaData = new Phalcon\Mvc\Model\Metadata\Xcache( + [ + "prefix" => "my-app-id", + "lifetime" => 86400, + ] + ); @@ -111,319 +117,423 @@ Return the strategy to obtain the meta-data final public **readMetaData** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the complete meta-data for certain model +Reads the complete meta-data for certain model .. code-block:: php readMetaData(new Robots()); + print_r( + $metaData->readMetaData( + new Robots() + ) + ); final public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads meta-data for certain model +Reads meta-data for certain model .. code-block:: php readMetaDataIndex(new Robots(), 0); + print_r( + $metaData->readMetaDataIndex( + new Robots(), + 0 + ) + ); final public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index, *mixed* $data) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Writes meta-data for certain model using a MODEL_* constant +Writes meta-data for certain model using a MODEL_* constant .. code-block:: php writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name'))); + print_r( + $metaData->writeColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP, + [ + "leName" => "name", + ] + ) + ); final public **readColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads the ordered/reversed column map for certain model +Reads the ordered/reversed column map for certain model .. code-block:: php readColumnMap(new Robots())); + print_r( + $metaData->readColumnMap( + new Robots() + ) + ); final public **readColumnMapIndex** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $index) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Reads column-map information for certain model using a MODEL_* constant +Reads column-map information for certain model using a MODEL_* constant .. code-block:: php readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP)); + print_r( + $metaData->readColumnMapIndex( + new Robots(), + MetaData::MODELS_REVERSE_COLUMN_MAP + ) + ); public **getAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns table attributes names (fields) +Returns table attributes names (fields) .. code-block:: php getAttributes(new Robots())); + print_r( + $metaData->getAttributes( + new Robots() + ) + ); public **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are part of the primary key +Returns an array of fields which are part of the primary key .. code-block:: php getPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getPrimaryKeyAttributes( + new Robots() + ) + ); public **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of fields which are not part of the primary key +Returns an array of fields which are not part of the primary key .. code-block:: php getNonPrimaryKeyAttributes(new Robots())); + print_r( + $metaData->getNonPrimaryKeyAttributes( + new Robots() + ) + ); public **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns an array of not null attributes +Returns an array of not null attributes .. code-block:: php getNotNullAttributes(new Robots())); + print_r( + $metaData->getNotNullAttributes( + new Robots() + ) + ); public **getDataTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their data types +Returns attributes and their data types .. code-block:: php getDataTypes(new Robots())); + print_r( + $metaData->getDataTypes( + new Robots() + ) + ); public **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes which types are numerical +Returns attributes which types are numerical .. code-block:: php getDataTypesNumeric(new Robots())); + print_r( + $metaData->getDataTypesNumeric( + new Robots() + ) + ); public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the name of identity field (if one is present) +Returns the name of identity field (if one is present) .. code-block:: php getIdentityField(new Robots())); + print_r( + $metaData->getIdentityField( + new Robots() + ) + ); public **getBindTypes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes and their bind data types +Returns attributes and their bind data types .. code-block:: php getBindTypes(new Robots())); + print_r( + $metaData->getBindTypes( + new Robots() + ) + ); public **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the INSERT SQL generation +Returns attributes that must be ignored from the INSERT SQL generation .. code-block:: php getAutomaticCreateAttributes(new Robots())); + print_r( + $metaData->getAutomaticCreateAttributes( + new Robots() + ) + ); public **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes that must be ignored from the UPDATE SQL generation +Returns attributes that must be ignored from the UPDATE SQL generation .. code-block:: php getAutomaticUpdateAttributes(new Robots())); + print_r( + $metaData->getAutomaticUpdateAttributes( + new Robots() + ) + ); public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the INSERT SQL generation +Set the attributes that must be ignored from the INSERT SQL generation .. code-block:: php setAutomaticCreateAttributes(new Robots(), array('created_at' => true)); + $metaData->setAutomaticCreateAttributes( + new Robots(), + [ + "created_at" => true, + ] + ); public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that must be ignored from the UPDATE SQL generation +Set the attributes that must be ignored from the UPDATE SQL generation .. code-block:: php setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true)); + $metaData->setAutomaticUpdateAttributes( + new Robots(), + [ + "modified_at" => true, + ] + ); public **setEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *array* $attributes) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Set the attributes that allow empty string values +Set the attributes that allow empty string values .. code-block:: php setEmptyStringAttributes(new Robots(), array('name' => true)); + $metaData->setEmptyStringAttributes( + new Robots(), + [ + "name" => true, + ] + ); public **getEmptyStringAttributes** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes allow empty strings +Returns attributes allow empty strings .. code-block:: php getEmptyStringAttributes(new Robots())); + print_r( + $metaData->getEmptyStringAttributes( + new Robots() + ) + ); public **getDefaultValues** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns attributes (which have default values) and their default values +Returns attributes (which have default values) and their default values .. code-block:: php getDefaultValues(new Robots())); + print_r( + $metaData->getDefaultValues( + new Robots() + ) + ); public **getColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the column map if any +Returns the column map if any .. code-block:: php getColumnMap(new Robots())); + print_r( + $metaData->getColumnMap( + new Robots() + ) + ); public **getReverseColumnMap** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Returns the reverse column map if any +Returns the reverse column map if any .. code-block:: php getReverseColumnMap(new Robots())); + print_r( + $metaData->getReverseColumnMap( + new Robots() + ) + ); public **hasAttribute** (:doc:`Phalcon\\Mvc\\ModelInterface ` $model, *mixed* $attribute) inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Check if a model has certain attribute +Check if a model has certain attribute .. code-block:: php hasAttribute(new Robots(), 'name')); + var_dump( + $metaData->hasAttribute( + new Robots(), + "name" + ) + ); public **isEmpty** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Checks if the internal meta-data container is empty +Checks if the internal meta-data container is empty .. code-block:: php isEmpty()); + var_dump( + $metaData->isEmpty() + ); public **reset** () inherited from :doc:`Phalcon\\Mvc\\Model\\MetaData ` -Resets internal meta-data in order to regenerate it +Resets internal meta-data in order to regenerate it .. code-block:: php diff --git a/zh/api/Phalcon_Mvc_Model_Query.rst b/zh/api/Phalcon_Mvc_Model_Query.rst index 96f41befaa33..110883ea46b6 100644 --- a/zh/api/Phalcon_Mvc_Model_Query.rst +++ b/zh/api/Phalcon_Mvc_Model_Query.rst @@ -8,24 +8,27 @@ Class **Phalcon\\Mvc\\Model\\Query** :raw-html:`Source on GitHub` -This class takes a PHQL intermediate representation and executes it. +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"; - } + $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b + WHERE b.name = :name: ORDER BY c.name"; + + $result = $manager->executeQuery( + $phql, + [ + "name" => "Lamborghini", + ] + ); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } @@ -105,7 +108,8 @@ Resolves an expression from its intermediate code into a string final protected **_getSelectColumn** (*array* $column) -Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex +Resolves a column from its intermediate representation into an array used to determine +if the resultset produced is simple or complex @@ -189,7 +193,8 @@ Analyzes a DELETE intermediate code and produces an array to be executed later public **parse** () -Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another +intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query diff --git a/zh/api/Phalcon_Mvc_Model_Query_Builder.rst b/zh/api/Phalcon_Mvc_Model_Query_Builder.rst index 236c2b8e835e..a9e5ad73f4a6 100644 --- a/zh/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/zh/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -8,30 +8,37 @@ Class **Phalcon\\Mvc\\Model\\Query\\Builder** :raw-html:`Source on GitHub` -Helps to create PHQL queries using an OO interface +Helps to create PHQL queries using an OO interface .. code-block:: php array('Users'), - 'columns' => array('id', 'name', 'status'), - 'conditions' => array( - array( + $params = [ + "models" => ["Users"], + "columns" => ["id", "name", "status"], + "conditions" => [ + [ "created > :min: AND created < :max:", - array("min" => '2013-01-01', 'max' => '2014-01-01'), - array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR), - ), - ), - // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'", - 'group' => array('id', 'name'), - 'having' => "name = 'Kamil'", - 'order' => array('name', 'id'), - 'limit' => 20, - 'offset' => 20, - // or 'limit' => array(20, 20), - ); + [ + "min" => "2013-01-01", + "max" => "2014-01-01", + ], + [ + "min" => PDO::PARAM_STR, + "max" => PDO::PARAM_STR, + ], + ], + ], + // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'", + "group" => ["id", "name"], + "having" => "name = 'Kamil'", + "order" => ["name", "id"], + "limit" => 20, + "offset" => 20, + // or "limit" => [20, 20], + ]; + $queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params); @@ -66,7 +73,7 @@ Returns the DependencyInjector container public **distinct** (*mixed* $distinct) -Sets SELECT DISTINCT / SELECT ALL flag +Sets SELECT DISTINCT / SELECT ALL flag .. code-block:: php @@ -86,15 +93,27 @@ Returns SELECT DISTINCT / SELECT ALL flag public **columns** (*mixed* $columns) -Sets the columns to be queried +Sets the columns to be queried .. code-block:: php columns("id, name"); - $builder->columns(array('id', 'name')); - $builder->columns(array('name', 'number' => 'COUNT(*)')); + + $builder->columns( + [ + "id", + "name", + ] + ); + + $builder->columns( + [ + "name", + "number" => "COUNT(*)", + ] + ); @@ -107,40 +126,59 @@ Return the columns to be queried public **from** (*mixed* $models) -Sets the models who makes part of the query +Sets the models who makes part of the query .. code-block:: php from('Robots'); - $builder->from(array('Robots', 'RobotsParts')); - $builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts')); + $builder->from("Robots"); + + $builder->from( + [ + "Robots", + "RobotsParts", + ] + ); + + $builder->from( + [ + "r" => "Robots", + "rp" => "RobotsParts", + ] + ); public **addFrom** (*mixed* $model, [*mixed* $alias], [*mixed* $with]) -Add a model to take part of the query +Add a model to take part of the query .. code-block:: php addFrom('Robots'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - $builder->addFrom('Robots', 'r'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load model 'RobotsParts' - $builder->addFrom('Robots', 'r', 'RobotsParts'); - - // Load data from model 'Robots' using 'r' as alias in PHQL - // and eager load models 'RobotsParts' and 'Parts' - $builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']); + // Load data from models Robots + $builder->addFrom("Robots"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + $builder->addFrom("Robots", "r"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load model 'RobotsParts' + $builder->addFrom("Robots", "r", "RobotsParts"); + + // Load data from model 'Robots' using 'r' as alias in PHQL + // and eager load models 'RobotsParts' and 'Parts' + $builder->addFrom( + "Robots", + "r", + [ + "RobotsParts", + "Parts", + ] + ); @@ -153,69 +191,69 @@ Return the models who makes part of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, [*string* $conditions], [*string* $alias], [*string* $type]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php join('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->join('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r'); - - // Left Join model 'Robots' specifing conditions, alias and type of join - $builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->join("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->join("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r"); + + // Left Join model 'Robots' specifying conditions, alias and type of join + $builder->join("Robots", "r.id = RobotsParts.robots_id", "r", "LEFT"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **innerJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds an INNER join to the query +Adds an INNER join to the query .. code-block:: php innerJoin('Robots'); - - // Inner Join model 'Robots' specifing conditions - $builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id'); - - // Inner Join model 'Robots' specifing conditions and alias - $builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + // Inner Join model 'Robots' with automatic conditions and alias + $builder->innerJoin("Robots"); + + // Inner Join model 'Robots' specifying conditions + $builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id"); + + // Inner Join model 'Robots' specifying conditions and alias + $builder->innerJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **leftJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a LEFT join to the query +Adds a LEFT join to the query .. code-block:: php leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->leftJoin("Robots", "r.id = RobotsParts.robots_id", "r"); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **rightJoin** (*string* $model, [*string* $conditions], [*string* $alias]) -Adds a RIGHT join to the query +Adds a RIGHT join to the query .. code-block:: php rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r'); + $builder->rightJoin("Robots", "r.id = RobotsParts.robots_id", "r"); @@ -228,95 +266,117 @@ Return join parts of the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*mixed* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Sets the query conditions +Sets the query conditions .. code-block:: php where(100); - $builder->where('name = "Peter"'); - $builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + + $builder->where("name = 'Peter'"); + + $builder->where( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **andWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using a AND operator +Appends a condition to the current conditions using a AND operator .. code-block:: php andWhere('name = "Peter"'); - $builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->andWhere("name = 'Peter'"); + + $builder->andWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orWhere** (*string* $conditions, [*array* $bindParams], [*array* $bindTypes]) -Appends a condition to the current conditions using an OR operator +Appends a condition to the current conditions using an OR operator .. code-block:: php orWhere('name = "Peter"'); - $builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100)); + $builder->orWhere("name = 'Peter'"); + + $builder->orWhere( + "name = :name: AND id > :id:", + [ + "name" => "Peter", + "id" => 100, + ] + ); public **betweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a BETWEEN condition to the current conditions +Appends a BETWEEN condition to the current conditions .. code-block:: php betweenWhere('price', 100.25, 200.50); + $builder->betweenWhere("price", 100.25, 200.50); public **notBetweenWhere** (*mixed* $expr, *mixed* $minimum, *mixed* $maximum, [*mixed* $operator]) -Appends a NOT BETWEEN condition to the current conditions +Appends a NOT BETWEEN condition to the current conditions .. code-block:: php notBetweenWhere('price', 100.25, 200.50); + $builder->notBetweenWhere("price", 100.25, 200.50); public **inWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends an IN condition to the current conditions +Appends an IN condition to the current conditions .. code-block:: php inWhere('id', [1, 2, 3]); + $builder->inWhere("id", [1, 2, 3]); public **notInWhere** (*mixed* $expr, *array* $values, [*mixed* $operator]) -Appends a NOT IN condition to the current conditions +Appends a NOT IN condition to the current conditions .. code-block:: php notInWhere('id', [1, 2, 3]); + $builder->notInWhere("id", [1, 2, 3]); @@ -329,14 +389,14 @@ Return the conditions for the query public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* | *array* $orderBy) -Sets an ORDER BY condition clause +Sets an ORDER BY condition clause .. code-block:: php orderBy('Robots.name'); - $builder->orderBy(array('1', 'Robots.name')); + $builder->orderBy("Robots.name"); + $builder->orderBy(["1", "Robots.name"]); @@ -349,20 +409,20 @@ Returns the set ORDER BY clause public **having** (*mixed* $having) -Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters +Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters .. code-block:: php having('SUM(Robots.price) > 0'); + $builder->having("SUM(Robots.price) > 0"); public **forUpdate** (*mixed* $forUpdate) -Sets a FOR UPDATE clause +Sets a FOR UPDATE clause .. code-block:: php @@ -379,9 +439,9 @@ Return the current having clause -public **limit** ([*mixed* $limit], [*mixed* $offset]) +public **limit** (*mixed* $limit, [*mixed* $offset]) -Sets a LIMIT clause, optionally an offset clause +Sets a LIMIT clause, optionally an offset clause .. code-block:: php @@ -389,6 +449,7 @@ Sets a LIMIT clause, optionally an offset clause $builder->limit(100); $builder->limit(100, 20); + $builder->limit("100", "20"); @@ -401,7 +462,7 @@ Returns the current LIMIT clause public **offset** (*mixed* $offset) -Sets an OFFSET clause +Sets an OFFSET clause .. code-block:: php @@ -420,13 +481,17 @@ Returns the current OFFSET clause public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* | *array* $group) -Sets a GROUP BY clause +Sets a GROUP BY clause .. code-block:: php groupBy(array('Robots.name')); + $builder->groupBy( + [ + "Robots.name", + ] + ); diff --git a/zh/api/Phalcon_Mvc_Model_Query_Lang.rst b/zh/api/Phalcon_Mvc_Model_Query_Lang.rst index f5f3b7eab8fc..9773c7e26b73 100644 --- a/zh/api/Phalcon_Mvc_Model_Query_Lang.rst +++ b/zh/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -6,13 +6,21 @@ Abstract class **Phalcon\\Mvc\\Model\\Query\\Lang** :raw-html:`Source on GitHub` -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. +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 Source on GitHub` -This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails +This class represents the status returned by a PHQL +statement like INSERT, UPDATE or DELETE. It offers context +information and the related messages produced by the +model which finally executes the operations when it fails .. 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'; + + $status = $app->modelsManager->executeQuery( + $phql, + [ + "id" => 100, + "name" => "Astroy Boy", + "type" => "mechanical", + "year" => 1959, + ] + ); + + // Check if the update was successful + if ($status->success() === true) { + echo "OK"; } diff --git a/zh/api/Phalcon_Mvc_Model_Relation.rst b/zh/api/Phalcon_Mvc_Model_Relation.rst index bbd49acbd3ac..7a0c5587b554 100644 --- a/zh/api/Phalcon_Mvc_Model_Relation.rst +++ b/zh/api/Phalcon_Mvc_Model_Relation.rst @@ -77,7 +77,8 @@ Returns the options public **getOption** (*mixed* $name) -Returns an option by the specified name If the option doesn't exist null is returned +Returns an option by the specified name +If the option doesn't exist null is returned diff --git a/zh/api/Phalcon_Mvc_Model_Resultset.rst b/zh/api/Phalcon_Mvc_Model_Resultset.rst index f4559335c865..784d0e4261f1 100644 --- a/zh/api/Phalcon_Mvc_Model_Resultset.rst +++ b/zh/api/Phalcon_Mvc_Model_Resultset.rst @@ -8,26 +8,44 @@ Abstract class **Phalcon\\Mvc\\Model\\Resultset** :raw-html:`Source on GitHub` -This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption Resultsets 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. +This component allows to Phalcon\\Mvc\\Model returns large resultsets with the minimum memory consumption +Resultsets 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(["type='virtual'", 'order' => 'name'); - $robots->rewind(); - while ($robots->valid()) { - $robot = $robots->current(); - echo $robot->name, "\n"; - $robots->next(); - } + // Using a standard foreach + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + foreach ($robots as robot) { + echo robot->name, "\n"; + } + + // Using a while + $robots = Robots::find( + [ + "type = 'virtual'", + "order" => "name", + ] + ); + + $robots->rewind(); + + while ($robots->valid()) { + $robot = $robots->current(); + + echo $robot->name, "\n"; + + $robots->next(); + } @@ -79,7 +97,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -181,31 +200,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required +Complex resultsets may include complete objects and scalar values. +This class builds every complex row as it is required Constants @@ -43,7 +44,8 @@ Returns current row in the resultset public **toArray** () -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. @@ -85,7 +87,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +190,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -Simple resultsets only contains a complete objects This class builds every complete object as it is required +Simple resultsets only contains a complete objects +This class builds every complete object as it is required Constants @@ -43,7 +44,9 @@ Returns current row in the resultset public **toArray** ([*mixed* $renameColumns]) -Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records +Returns a complete resultset as an array, if the resultset has a big number of rows +it could consume more memory than currently it does. Export the resultset to an array +couldn't be faster with a large number of records @@ -85,7 +88,8 @@ Rewinds resultset to its beginning final public **seek** (*mixed* $position) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row +Changes internal pointer to a specific position in the resultset +Set new position if required and set this->_row @@ -187,31 +191,34 @@ Deletes every record in the resultset public :doc:`Phalcon\\Mvc\\Model `\ [] **filter** (*callback* $filter) inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Filters a resultset returning only those the developer requires +Filters a resultset returning only those the developer requires .. code-block:: php filter(function($robot){ - if ($robot->id < 3) { - return $robot; - } - }); + $filtered = $robots->filter( + function ($robot) { + if ($robot->id < 3) { + return $robot; + } + } + ); public *array* **jsonSerialize** () inherited from :doc:`Phalcon\\Mvc\\Model\\Resultset ` -Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present +Returns serialised model objects as array for json_encode. +Calls jsonSerialize on each object if present .. code-block:: php Source on GitHub` -This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. +This objects implements the ArrayAccess interface to allow access the object as object->x or array[x]. Methods @@ -46,26 +47,26 @@ Rows cannot be changed. It has only been implemented to meet the definition of t public *mixed* **readAttribute** (*string* $attribute) -Reads an attribute value by its name +Reads an attribute value by its name .. code-block:: php readAttribute('name'); + echo $robot->readAttribute("name"); public **writeAttribute** (*string* $attribute, *mixed* $value) -Writes an attribute value by its name +Writes an attribute value by its name .. code-block:: php writeAttribute('name', 'Rosey'); + $robot->writeAttribute("name", "Rosey"); diff --git a/zh/api/Phalcon_Mvc_Model_Transaction.rst b/zh/api/Phalcon_Mvc_Model_Transaction.rst index 768931b2da0d..42c48af22e59 100644 --- a/zh/api/Phalcon_Mvc_Model_Transaction.rst +++ b/zh/api/Phalcon_Mvc_Model_Transaction.rst @@ -8,37 +8,43 @@ Class **Phalcon\\Mvc\\Model\\Transaction** :raw-html:`Source on GitHub` -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. +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 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(); - + $manager = new \Phalcon\Mvc\Model\Transaction\Manager(); + + $transaction = $manager->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(); + echo "Failed, reason: ", $e->getMessage(); } diff --git a/zh/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/zh/api/Phalcon_Mvc_Model_Transaction_Manager.rst index fcfb028f7a95..068464a66a00 100644 --- a/zh/api/Phalcon_Mvc_Model_Transaction_Manager.rst +++ b/zh/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -8,39 +8,48 @@ Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** :raw-html:`Source on GitHub` -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 transaction produces a unique connection that is passed to every object part of the transaction. +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 transaction 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(); - + use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager; + + $transactionManager = new TransactionManager(); + + $transaction = $transactionManager->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(); + echo "Failed, reason: ", $e->getMessage(); } @@ -98,7 +107,8 @@ Checks whether the manager has an active transaction public **get** ([*mixed* $autoBegin]) -Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once This method registers a shutdown function to rollback active connections +Returns a new \\Phalcon\\Mvc\\Model\\Transaction or an already created once +This method registers a shutdown function to rollback active connections @@ -122,7 +132,8 @@ Commits active transactions within the manager public **rollback** ([*boolean* $collect]) -Rollbacks active transactions within the manager Collect will remove the transaction from the manager +Rollbacks active transactions within the manager +Collect will remove the transaction from the manager diff --git a/zh/api/Phalcon_Mvc_Model_ValidationFailed.rst b/zh/api/Phalcon_Mvc_Model_ValidationFailed.rst index 839ebff79617..60139a201705 100644 --- a/zh/api/Phalcon_Mvc_Model_ValidationFailed.rst +++ b/zh/api/Phalcon_Mvc_Model_ValidationFailed.rst @@ -10,7 +10,8 @@ Class **Phalcon\\Mvc\\Model\\ValidationFailed** :raw-html:`Source on GitHub` -This exception is generated when a model fails to save a record Phalcon\\Mvc\\Model must be set up to have this behavior +This exception is generated when a model fails to save a record +Phalcon\\Mvc\\Model must be set up to have this behavior Methods diff --git a/zh/api/Phalcon_Mvc_Model_Validator.rst b/zh/api/Phalcon_Mvc_Model_Validator.rst index 6042bd4e5d01..15491363b5cd 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** ================================================= +*implements* :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + .. role:: raw-html(raw) :format: html @@ -8,6 +10,9 @@ Abstract class **Phalcon\\Mvc\\Model\\Validator** This is a base class for Phalcon\\Mvc\\Model validators +This class is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. + Methods ------- @@ -48,3 +53,8 @@ Check whether an option has been defined in the validator options +abstract public **validate** (:doc:`Phalcon\\Mvc\\EntityInterface ` $record) inherited from :doc:`Phalcon\\Mvc\\Model\\ValidatorInterface ` + +... + + diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Email.rst b/zh/api/Phalcon_Mvc_Model_Validator_Email.rst index 50c2f055ecc0..a4f836906923 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator_Email.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -10,26 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Email** :raw-html:`Source on GitHub` -Allows to validate if email fields has correct values +Allows to validate if email fields has correct values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new EmailValidator(array( - 'field' => 'electronic_mail' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new EmailValidator( + [ + "field" => "electronic_mail", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/zh/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst index b83a034c2afc..e2f38b4a9e48 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn + +Check if a value is not included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new ExclusionInValidator(array( - 'field' => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new ExclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/zh/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst index a643654ece22..3128a90941b7 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values +Phalcon\\Mvc\\Model\\Validator\\InclusionIn + +Check if a value is included into a list of values + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new InclusionInValidator(array( - "field" => 'status', - 'domain' => array('A', 'I') - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new InclusionInValidator( + [ + "field" => "status", + "domain" => ["A", "I"], + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Ip.rst b/zh/api/Phalcon_Mvc_Model_Validator_Ip.rst index c3c1fc842a5a..07750cc6a79d 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator_Ip.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator_Ip.rst @@ -10,48 +10,63 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Ip** :raw-html:`Source on GitHub` -Phalcon\\Mvc\\Model\\Validator\\IP Validates that a value is ipv4 address in valid range +Phalcon\\Mvc\\Model\\Validator\\IP + +Validates that a value is ipv4 address in valid range + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new IP(array( - 'field' => 'server_ip', - 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified - 'allowReserved' => false, // False if not specified. Ignored for v6 - 'allowPrivate' => false, // False if not specified - 'message' => 'IP address has to be correct' - ))); - - // Any public v4 address - $this->validate(new IP(array( - 'field' => 'ip_4', - 'version' => IP::VERSION_4, - 'message' => 'IP address has to be correct' - ))); - - // Any v6 address - $this->validate(new IP(array( - 'field' => 'ip6', - 'version' => IP::VERSION_6, - 'allowPrivate' => true, - 'message' => 'IP address has to be correct' - ))); - - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + // Any pubic IP + $this->validate( + new IP( + [ + "field" => "server_ip", + "version" => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified + "allowReserved" => false, // False if not specified. Ignored for v6 + "allowPrivate" => false, // False if not specified + "message" => "IP address has to be correct", + ] + ) + ); + + // Any public v4 address + $this->validate( + new IP( + [ + "field" => "ip_4", + "version" => IP::VERSION_4, + "message" => "IP address has to be correct", + ] + ) + ); + + // Any v6 address + $this->validate( + new IP( + [ + "field" => "ip6", + "version" => IP::VERSION_6, + "allowPrivate" => true, + "message" => "IP address has to be correct", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/zh/api/Phalcon_Mvc_Model_Validator_Numericality.rst index 5279c27fe2a2..53e627143918 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator_Numericality.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** :raw-html:`Source on GitHub` -Allows to validate if a field has a valid numeric format +Allows to validate if a field has a valid numeric format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new NumericalityValidator(array( - "field" => 'price' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new NumericalityValidator( + [ + "field" => "price", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/zh/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/zh/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst index 05f7621143bf..bc2269a9c69f 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Allows to validate if a filed have a value different of null and empty string ("") +Allows to validate if a filed have a value different of null and empty string ("") + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new PresenceOf(array( - "field" => 'name', - "message" => 'The name is required' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new PresenceOf( + [ + "field" => "name", + "message" => "The name is required", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Regex.rst b/zh/api/Phalcon_Mvc_Model_Validator_Regex.rst index c4aec2371fca..3deb624de794 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator_Regex.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -10,28 +10,34 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. 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; - } - } - + public function validation() + { + $this->validate( + new RegexValidator( + [ + "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; + } + } } diff --git a/zh/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/zh/api/Phalcon_Mvc_Model_Validator_StringLength.rst index 77edade14799..1d4f717b3e87 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator_StringLength.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** :raw-html:`Source on GitHub` -Simply validates specified string length constraints +Simply validates specified string length constraints + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new StringLengthValidator(array( - "field" => 'name_last', - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new StringLengthValidator( + [ + "field" => "name_last", + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/zh/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst index d9f5e362ed21..be83d8ab1982 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -10,28 +10,36 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -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 +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 + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new Uniqueness(array( - "field" => "email", - "message" => "Value of field 'email' is already present in another record" - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } + public function validation() + { + $this->validate( + new Uniqueness( + [ + "field" => "email", + "message" => "Value of field 'email' is already present in another record", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Url.rst b/zh/api/Phalcon_Mvc_Model_Validator_Url.rst index e8c71c2de40e..8990f230539e 100644 --- a/zh/api/Phalcon_Mvc_Model_Validator_Url.rst +++ b/zh/api/Phalcon_Mvc_Model_Validator_Url.rst @@ -10,27 +10,33 @@ Class **Phalcon\\Mvc\\Model\\Validator\\Url** :raw-html:`Source on GitHub` -Allows to validate if a field has a url format +Allows to validate if a field has a url format + +This validator is only for use with Phalcon\\Mvc\\Collection. If you are using +Phalcon\\Mvc\\Model, please use the validators provided by Phalcon\\Validation. .. code-block:: php validate(new UrlValidator(array( - 'field' => 'source_url' - ))); - if ($this->validationHasFailed() == true) { - return false; - } - } - + public function validation() + { + $this->validate( + new UrlValidator( + [ + "field" => "source_url", + ] + ) + ); + + if ($this->validationHasFailed() === true) { + return false; + } + } } diff --git a/zh/api/Phalcon_Mvc_Router.rst b/zh/api/Phalcon_Mvc_Router.rst index 16c0b9a0758d..1ee35b415bb3 100644 --- a/zh/api/Phalcon_Mvc_Router.rst +++ b/zh/api/Phalcon_Mvc_Router.rst @@ -8,27 +8,30 @@ Class **Phalcon\\Mvc\\Router** :raw-html:`Source on GitHub` -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 +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 add( - '/documentation/{chapter}/{name}\.{type:[a-z]+}', - [ - 'controller' => 'documentation', - 'action' => 'show' - ) + use Phalcon\Mvc\Router; + + $router = new Router(); + + $router->add( + "/documentation/{chapter}/{name}\.{type:[a-z]+}", + [ + "controller" => "documentation", + "action" => "show", + ] ); - - $router->handle(); - - echo $router->getControllerName(); + + $router->handle(); + + echo $router->getControllerName(); @@ -78,19 +81,21 @@ Returns the internal event manager public **getRewriteUri** () -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -127,16 +132,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -149,34 +157,34 @@ Returns an array of default parameters public **handle** ([*mixed* $uri]) -Handles routing information received from the rewrite engine +Handles routing information received from the rewrite engine .. code-block:: php handle(); - - // Manually passing an URL - $router->handle('/posts/edit/1'); + // Read the info from the rewrite engine + $router->handle(); + + // Manually passing an URL + $router->handle("/posts/edit/1"); public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/zh/api/Phalcon_Mvc_Router_Annotations.rst b/zh/api/Phalcon_Mvc_Router_Annotations.rst index 9d113171ce26..c9e5436879ba 100644 --- a/zh/api/Phalcon_Mvc_Router_Annotations.rst +++ b/zh/api/Phalcon_Mvc_Router_Annotations.rst @@ -10,22 +10,26 @@ Class **Phalcon\\Mvc\\Router\\Annotations** :raw-html:`Source on GitHub` -A router that reads routes annotations from classes/resources +A router that reads routes annotations from classes/resources .. code-block:: php addResource('Robots', '/robots'); - - return $router; - }; + use Phalcon\Mvc\Router\Annotations; + + $di->setShared( + "router", + function() { + // Use the annotations router + $router = new Annotations(false); + + // This will do the same as above but only if the handled uri starts with /robots + $router->addResource("Robots", "/robots"); + + return $router; + } + ); @@ -45,13 +49,16 @@ Methods public **addResource** (*mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations +Adds a resource to the annotations handler +A resource is a class that contains routing annotations public **addModuleResource** (*mixed* $module, *mixed* $handler, [*mixed* $prefix]) -Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module +Adds a resource to the annotations handler +A resource is a class that contains routing annotations +The class is located in a module @@ -123,19 +130,21 @@ Returns the internal event manager public **getRewriteUri** () inherited from :doc:`Phalcon\\Mvc\\Router ` -Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read +Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read public **setUriSource** (*mixed* $uriSource) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets the URI source. One of the URI_SOURCE_* constants +Sets the URI source. One of the URI_SOURCE_* constants .. code-block:: php setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI); + $router->setUriSource( + Router::URI_SOURCE_SERVER_REQUEST_URI + ); @@ -172,16 +181,19 @@ Sets the default action name public **setDefaults** (*array* $defaults) inherited from :doc:`Phalcon\\Mvc\\Router ` -Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route +Sets an array of default paths. If a route is missing a path the router will use the defined here +This method must not be used to set a 404 route .. code-block:: php setDefaults([ - 'module' => 'common', - 'action' => 'index' - ]); + $router->setDefaults( + [ + "module" => "common", + "action" => "index", + ] + ); @@ -194,17 +206,17 @@ Returns an array of default parameters public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods], [*mixed* $position]) inherited from :doc:`Phalcon\\Mvc\\Router ` -Adds a route to the router without any HTTP constraint +Adds a route to the router without any HTTP constraint .. code-block:: php add('/about', 'About::index'); - $router->add('/about', 'About::index', ['GET', 'POST']); - $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST); + use Phalcon\Mvc\Router; + + $router->add("/about", "About::index"); + $router->add("/about", "About::index", ["GET", "POST"]); + $router->add("/about", "About::index", ["GET", "POST"], Router::POSITION_FIRST); diff --git a/zh/api/Phalcon_Mvc_Router_Group.rst b/zh/api/Phalcon_Mvc_Router_Group.rst index 8a437f952bdc..10f9a7590bc6 100644 --- a/zh/api/Phalcon_Mvc_Router_Group.rst +++ b/zh/api/Phalcon_Mvc_Router_Group.rst @@ -8,41 +8,52 @@ Class **Phalcon\\Mvc\\Router\\Group** :raw-html:`Source on GitHub` -Helper class to create a group of routes with common attributes +Helper class to create a group of routes with common attributes .. code-block:: php 'blog', - 'controller' => 'index' - )); - - //All the routes start with /blog - $blog->setPrefix('/blog'); - - //Add a route to the group - $blog->add('/save', array( - 'action' => 'save' - )); - - //Add another route to the group - $blog->add('/edit/{id}', array( - 'action' => 'edit' - )); - - //This route maps to a controller different than the default - $blog->add('/blog', array( - 'controller' => 'about', - 'action' => 'index' - )); - - //Add the group to the router - $router->mount($blog); + $router = new \Phalcon\Mvc\Router(); + + //Create a group with a common module and controller + $blog = new Group( + [ + "module" => "blog", + "controller" => "index", + ] + ); + + //All the routes start with /blog + $blog->setPrefix("/blog"); + + //Add a route to the group + $blog->add( + "/save", + [ + "action" => "save", + ] + ); + + //Add another route to the group + $blog->add( + "/edit/{id}", + [ + "action" => "edit", + ] + ); + + //This route maps to a controller different than the default + $blog->add( + "/blog", + [ + "controller" => "about", + "action" => "index", + ] + ); + + //Add the group to the router + $router->mount($blog); @@ -81,7 +92,9 @@ Returns the common prefix for all the routes public **beforeMatch** (*mixed* $beforeMatch) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched @@ -111,13 +124,13 @@ Returns the routes added to the group public **add** (*mixed* $pattern, [*mixed* $paths], [*mixed* $httpMethods]) -Adds a route to the router on any HTTP method +Adds a route to the router on any HTTP method .. code-block:: php add('/about', 'About::index'); + $router->add("/about", "About::index"); diff --git a/zh/api/Phalcon_Mvc_Router_Route.rst b/zh/api/Phalcon_Mvc_Router_Route.rst index de2691739435..2bf45df7521b 100644 --- a/zh/api/Phalcon_Mvc_Router_Route.rst +++ b/zh/api/Phalcon_Mvc_Router_Route.rst @@ -28,14 +28,20 @@ Replaces placeholders from pattern returning a valid PCRE regular expression public **via** (*mixed* $httpMethods) -Set one or more HTTP methods that constraint the matching of the route +Set one or more HTTP methods that constraint the matching of the route .. code-block:: php via('GET'); - $route->via(array('GET', 'POST')); + $route->via("GET"); + + $route->via( + [ + "GET", + "POST", + ] + ); @@ -66,37 +72,48 @@ Returns the route's name public **setName** (*mixed* $name) -Sets the route's name +Sets the route's name .. code-block:: php add('/about', array( - 'controller' => 'about' - ))->setName('about'); + $router->add( + "/about", + [ + "controller" => "about", + ] + )->setName("about"); public **beforeMatch** (*mixed* $callback) -Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched +Sets a callback that is called if the route is matched. +The developer can implement any arbitrary conditions here +If the callback returns false the route is treated as not matched .. code-block:: php add('/login', array( - 'module' => 'admin', - 'controller' => 'session' - ))->beforeMatch(function ($uri, $route) { - // Check if the request was made with Ajax - if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') { - return false; - } - return true; - }); + $router->add( + "/login", + [ + "module" => "admin", + "controller" => "session", + ] + )->beforeMatch( + function ($uri, $route) { + // Check if the request was made with Ajax + if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") { + return false; + } + + return true; + } + ); @@ -109,15 +126,20 @@ Returns the 'before match' callback if any public **match** (*mixed* $callback) -Allows to set a callback to handle the request directly in the route +Allows to set a callback to handle the request directly in the route .. code-block:: php add("/help", array())->match(function () { - return $this->getResponse()->redirect('https://support.google.com/', true); - }); + $router->add( + "/help", + [] + )->match( + function () { + return $this->getResponse()->redirect("https://support.google.com/", true); + } + ); @@ -160,14 +182,14 @@ Returns the paths using positions as keys and names as values public **setHttpMethods** (*mixed* $httpMethods) -Sets a set of HTTP methods that constraint the matching of the route (alias of via) +Sets a set of HTTP methods that constraint the matching of the route (alias of via) .. code-block:: php setHttpMethods('GET'); - $route->setHttpMethods(array('GET', 'POST')); + $route->setHttpMethods("GET"); + $route->setHttpMethods(["GET", "POST"]); @@ -180,13 +202,13 @@ Returns the HTTP methods that constraint matching the route public **setHostname** (*mixed* $hostname) -Sets a hostname restriction to the route +Sets a hostname restriction to the route .. code-block:: php setHostname('localhost'); + $route->setHostname("localhost"); diff --git a/zh/api/Phalcon_Mvc_Url.rst b/zh/api/Phalcon_Mvc_Url.rst index 1a9ee6436ea2..cf885c422ebe 100644 --- a/zh/api/Phalcon_Mvc_Url.rst +++ b/zh/api/Phalcon_Mvc_Url.rst @@ -8,17 +8,23 @@ Class **Phalcon\\Mvc\\Url** :raw-html:`Source on GitHub` -This components helps in the generation of: URIs, URLs and Paths +This components helps 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')); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2012", + ] + ); @@ -39,27 +45,28 @@ Returns the DependencyInjector container public **setBaseUri** (*mixed* $baseUri) -Sets a prefix for all the URIs to be generated +Sets a prefix for all the URIs to be generated .. code-block:: php setBaseUri('/invo/'); - $url->setBaseUri('/invo/index.php/'); + $url->setBaseUri("/invo/"); + + $url->setBaseUri("/invo/index.php/"); public **setStaticBaseUri** (*mixed* $staticBaseUri) -Sets a prefix for all static URLs generated +Sets a prefix for all static URLs generated .. code-block:: php setStaticBaseUri('/invo/'); + $url->setStaticBaseUri("/invo/"); @@ -78,13 +85,13 @@ Returns the prefix for all the generated static urls. By default / public **setBasePath** (*mixed* $basePath) -Sets a base path for all the generated paths +Sets a base path for all the generated paths .. code-block:: php setBasePath('/var/www/htdocs/'); + $url->setBasePath("/var/www/htdocs/"); @@ -97,40 +104,60 @@ Returns the base path public **get** ([*mixed* $uri], [*mixed* $args], [*mixed* $local], [*mixed* $baseUri]) -Generates a URL +Generates a URL .. 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' => '2015')); - - // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) - echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots')); - - // Generate an absolute URL by setting the third parameter as false. - echo $url->get('https://phalconphp.com/', null, false); + // Generate a URL appending the URI to the base URI + echo $url->get("products/edit/1"); + + // Generate a URL for a predefined route + echo $url->get( + [ + "for" => "blog-post", + "title" => "some-cool-stuff", + "year" => "2015", + ] + ); + + // Generate a URL with GET arguments (/show/products?id=1&name=Carrots) + echo $url->get( + "show/products", + [ + "id" => 1, + "name" => "Carrots", + ] + ); + + // Generate an absolute URL by setting the third parameter as false. + echo $url->get( + "https://phalconphp.com/", + null, + false + ); public **getStatic** ([*mixed* $uri]) -Generates a URL for a static resource +Generates a URL for a static resource .. code-block:: php getStatic("img/logo.png"); - - // Generate a URL for a static predefined route - echo $url->getStatic(array('for' => 'logo-cdn')); + // Generate a URL for a static resource + echo $url->getStatic("img/logo.png"); + + // Generate a URL for a static predefined route + echo $url->getStatic( + [ + "for" => "logo-cdn", + ] + ); diff --git a/zh/api/Phalcon_Mvc_View.rst b/zh/api/Phalcon_Mvc_View.rst index d84d46681f6e..0eff227d59c4 100644 --- a/zh/api/Phalcon_Mvc_View.rst +++ b/zh/api/Phalcon_Mvc_View.rst @@ -10,27 +10,29 @@ Class **Phalcon\\Mvc\\View** :raw-html:`Source on GitHub` -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. +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(); + use Phalcon\Mvc\View; + + $view = new View(); + + // Setting views directory + $view->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(); @@ -86,7 +88,8 @@ Checks if a path is absolute or not public **setViewsDir** (*mixed* $viewsDir) -Sets the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the views directory. Depending of your platform, +always add a trailing slash or backslash @@ -98,13 +101,14 @@ Gets views directory public **setLayoutsDir** (*mixed* $layoutsDir) -Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets the layouts sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setLayoutsDir('../common/layouts/'); + $view->setLayoutsDir("../common/layouts/"); @@ -117,13 +121,14 @@ Gets the current layouts sub-directory public **setPartialsDir** (*mixed* $partialsDir) -Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash +Sets a partials sub-directory. Must be a directory under the views directory. +Depending of your platform, always add a trailing slash or backslash .. code-block:: php setPartialsDir('../common/partials/'); + $view->setPartialsDir("../common/partials/"); @@ -136,13 +141,13 @@ Gets the current partials sub-directory public **setBasePath** (*mixed* $basePath) -Sets base path. Depending of your platform, always add a trailing slash or backslash +Sets base path. Depending of your platform, always add a trailing slash or backslash .. code-block:: php setBasePath(__DIR__ . '/'); + $view->setBasePath(__DIR__ . "/"); @@ -155,42 +160,46 @@ Gets base path public **setRenderLevel** (*mixed* $level) -Sets the render level for the view +Sets the render level for the view .. code-block:: php view->setRenderLevel(View::LEVEL_LAYOUT); + // Render the view related to the controller only + $this->view->setRenderLevel( + View::LEVEL_LAYOUT + ); public **disableLevel** (*mixed* $level) -Disables a specific level of rendering +Disables a specific level of rendering .. code-block:: php view->disableLevel(View::LEVEL_ACTION_VIEW); + // Render all levels except ACTION level + $this->view->disableLevel( + View::LEVEL_ACTION_VIEW + ); public **setMainView** (*mixed* $viewPath) -Sets default view name. Must be a file without extension in the views directory +Sets default view name. Must be a file without extension in the views directory .. code-block:: php view->setMainView('base'); + // Renders as main view views-dir/base.phtml + $this->view->setMainView("base"); @@ -203,13 +212,13 @@ Returns the name of the main view public **setLayout** (*mixed* $layout) -Change the layout to be used instead of using the name of the latest controller name +Change the layout to be used instead of using the name of the latest controller name .. code-block:: php view->setLayout('main'); + $this->view->setLayout("main"); @@ -246,39 +255,43 @@ Resets any template before layouts public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -333,17 +346,19 @@ Checks whether view exists on registered extensions and render it public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -356,95 +371,109 @@ Checks whether view exists public **render** (*string* $controllerName, *string* $actionName, [*array* $params]) -Executes render process from dispatching data +Executes render process from dispatching data .. code-block:: php start()->render('posts', 'recent')->finish(); + // Shows recent posts view (app/views/posts/recent.phtml) + $view->start()->render("posts", "recent")->finish(); public **pick** (*mixed* $renderView) -Choose a different view to render instead of last-controller/last-action +Choose a different view to render instead of last-controller/last-action .. code-block:: php view->pick("products/list"); - } - } + use Phalcon\Mvc\Controller; + + class ProductsController extends Controller + { + public function saveAction() + { + // Do some save stuff... + + // Then show the list view + $this->view->pick("products/list"); + } + } public **getPartial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php getPartial('shared/footer'); + // Retrieve the contents of a partial + echo $this->getPartial("shared/footer"); .. code-block:: php getPartial('shared/footer', ['content' => $html]); + // Retrieve the contents of a partial with arguments + echo $this->getPartial( + "shared/footer", + [ + "content" => $html, + ] + ); public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); public *string* **getRender** (*string* $controllerName, *string* $actionName, [*array* $params], [*mixed* $configCallback]) -Perform the automatic rendering returning the output as a string +Perform the automatic rendering returning the output as a string .. code-block:: php view->getRender('products', 'show', ['products' => $products]); + $template = $this->view->getRender( + "products", + "show", + [ + "products" => $products, + ] + ); @@ -475,20 +504,25 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -531,7 +565,7 @@ Resets the view component to its factory default values public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -544,7 +578,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php @@ -563,13 +597,13 @@ Whether automatic rendering is enabled public **__isset** (*mixed* $key) -Magic method to retrieve if a variable is set in the view +Magic method to retrieve if a variable is set in the view .. code-block:: php view->products); + echo isset($this->view->products); diff --git a/zh/api/Phalcon_Mvc_View_Engine.rst b/zh/api/Phalcon_Mvc_View_Engine.rst index eaf95c8534f6..9607a76544cc 100644 --- a/zh/api/Phalcon_Mvc_View_Engine.rst +++ b/zh/api/Phalcon_Mvc_View_Engine.rst @@ -3,14 +3,15 @@ Abstract class **Phalcon\\Mvc\\View\\Engine** *extends* abstract class :doc:`Phalcon\\Di\\Injectable ` -*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface ` +*implements* :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` .. role:: raw-html(raw) :format: html :raw-html:`Source on GitHub` -All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. +All the template engine adapters must inherit this class. This provides +basic interfacing between the engine and the Phalcon\\Mvc\\View component. Methods @@ -70,3 +71,8 @@ Magic method __get +abstract public **render** (*mixed* $path, *mixed* $params, [*mixed* $mustClean]) inherited from :doc:`Phalcon\\Mvc\\View\\EngineInterface ` + +... + + diff --git a/zh/api/Phalcon_Mvc_View_Engine_Php.rst b/zh/api/Phalcon_Mvc_View_Engine_Php.rst index 7ee7c36c4798..736e1bd41bbc 100644 --- a/zh/api/Phalcon_Mvc_View_Engine_Php.rst +++ b/zh/api/Phalcon_Mvc_View_Engine_Php.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Php** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/zh/api/Phalcon_Mvc_View_Engine_Volt.rst b/zh/api/Phalcon_Mvc_View_Engine_Volt.rst index 52314f46e707..d88d0691f88d 100644 --- a/zh/api/Phalcon_Mvc_View_Engine_Volt.rst +++ b/zh/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -3,7 +3,7 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt** *extends* abstract class :doc:`Phalcon\\Mvc\\View\\Engine ` -*implements* :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface `, :doc:`Phalcon\\Mvc\\View\\EngineInterface ` +*implements* :doc:`Phalcon\\Mvc\\View\\EngineInterface `, :doc:`Phalcon\\Di\\InjectionAwareInterface `, :doc:`Phalcon\\Events\\EventsAwareInterface ` .. role:: raw-html(raw) :format: html diff --git a/zh/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/zh/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 8b838100b96a..ec2c66068a09 100644 --- a/zh/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/zh/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -8,16 +8,16 @@ Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** :raw-html:`Source on GitHub` -This class reads and compiles Volt templates into PHP plain code +This class reads and compiles Volt templates into PHP plain code .. code-block:: php compile('views/partials/header.volt'); - + + $compiler->compile("views/partials/header.volt"); + require $compiler->getCompiledTemplatePath(); @@ -249,39 +249,41 @@ Compiles a Volt source code returning a PHP plain version public **compileString** (*mixed* $viewCode, [*mixed* $extendsMode]) -Compiles a template into a string +Compiles a template into a string .. code-block:: php compileString('{{ "hello world" }}'); + echo $compiler->compileString('{{ "hello world" }}'); public *string* | *array* **compileFile** (*string* $path, *string* $compiledPath, [*boolean* $extendsMode]) -Compiles a template into a file forcing the destination path +Compiles a template into a file forcing the destination path .. code-block:: php compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); + $compiler->compile("views/layouts/main.volt", "views/layouts/main.volt.php"); public **compile** (*mixed* $templatePath, [*mixed* $extendsMode]) -Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled +Compiles a template into a file applying the compiler options +This method does not return the compiled path if the template was not compiled .. code-block:: php compile('views/layouts/main.volt'); + $compiler->compile("views/layouts/main.volt"); + require $compiler->getCompiledTemplatePath(); @@ -301,13 +303,15 @@ Returns the path to the last compiled template public *array* **parse** (*string* $viewCode) -Parses a Volt template returning its intermediate representation +Parses a Volt template returning its intermediate representation .. code-block:: php parse('{{ 3 + 2 }}')); + print_r( + $compiler->parse("{{ 3 + 2 }}") + ); diff --git a/zh/api/Phalcon_Mvc_View_Simple.rst b/zh/api/Phalcon_Mvc_View_Simple.rst index b4faf4a6be3a..3334e8bc1223 100644 --- a/zh/api/Phalcon_Mvc_View_Simple.rst +++ b/zh/api/Phalcon_Mvc_View_Simple.rst @@ -10,21 +10,31 @@ Class **Phalcon\\Mvc\\View\\Simple** :raw-html:`Source on GitHub` -This component allows to render views without hierarchical levels +This component allows to render views without hierarchical levels .. code-block:: php render('templates/my-view', ['some' => $param]); - - // Or with filename with extension - echo $view->render('templates/my-view.volt', ['parameter' => $here]); + use Phalcon\Mvc\View\Simple as View; + + $view = new View(); + + // Render a view + echo $view->render( + "templates/my-view", + [ + "some" => $param, + ] + ); + + // Or with filename with extension + echo $view->render( + "templates/my-view.volt", + [ + "parameter" => $here, + ] + ); @@ -57,17 +67,19 @@ Gets views directory public **registerEngines** (*array* $engines) -Register templating engines +Register templating engines .. code-block:: php view->registerEngines([ - '.phtml' => 'Phalcon\Mvc\View\Engine\Php', - '.volt' => 'Phalcon\Mvc\View\Engine\Volt', - '.mhtml' => 'MyCustomEngine' - ]); + $this->view->registerEngines( + [ + ".phtml" => "Phalcon\\Mvc\\View\\Engine\\Php", + ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt", + ".mhtml" => "MyCustomEngine", + ] + ); @@ -92,21 +104,26 @@ Renders a view public **partial** (*mixed* $partialPath, [*mixed* $params]) -Renders a partial view +Renders a partial view .. code-block:: php partial('shared/footer'); + // Show a partial inside another view + $this->partial("shared/footer"); .. code-block:: php partial('shared/footer', ['content' => $html]); + // Show a partial inside another view with parameters + $this->partial( + "shared/footer", + [ + "content" => $html, + ] + ); @@ -137,52 +154,61 @@ Returns the cache instance used to cache public **cache** ([*mixed* $options]) -Cache the actual view render to certain level +Cache the actual view render to certain level .. code-block:: php view->cache(['key' => 'my-key', 'lifetime' => 86400]); + $this->view->cache( + [ + "key" => "my-key", + "lifetime" => 86400, + ] + ); public **setParamToView** (*mixed* $key, *mixed* $value) -Adds parameters to views (alias of setVar) +Adds parameters to views (alias of setVar) .. code-block:: php view->setParamToView('products', $products); + $this->view->setParamToView("products", $products); public **setVars** (*array* $params, [*mixed* $merge]) -Set all the render params +Set all the render params .. code-block:: php view->setVars(['products' => $products]); + $this->view->setVars( + [ + "products" => $products, + ] + ); public **setVar** (*mixed* $key, *mixed* $value) -Set a single view parameter +Set a single view parameter .. code-block:: php view->setVar('products', $products); + $this->view->setVar("products", $products); @@ -201,7 +227,7 @@ Returns parameters to views public **setContent** (*mixed* $content) -Externally sets the view content +Externally sets the view content .. code-block:: php @@ -226,7 +252,7 @@ Returns the path of the view that is currently rendered public **__set** (*mixed* $key, *mixed* $value) -Magic method to pass variables to the views +Magic method to pass variables to the views .. code-block:: php @@ -239,7 +265,7 @@ Magic method to pass variables to the views public **__get** (*mixed* $key) -Magic method to retrieve a variable passed to the view +Magic method to retrieve a variable passed to the view .. code-block:: php diff --git a/zh/api/Phalcon_Paginator_Adapter.rst b/zh/api/Phalcon_Paginator_Adapter.rst index 61a38b46c65b..1e31b00ac0c9 100644 --- a/zh/api/Phalcon_Paginator_Adapter.rst +++ b/zh/api/Phalcon_Paginator_Adapter.rst @@ -1,6 +1,8 @@ Abstract class **Phalcon\\Paginator\\Adapter** ============================================== +*implements* :doc:`Phalcon\\Paginator\\AdapterInterface ` + .. role:: raw-html(raw) :format: html @@ -30,3 +32,8 @@ Get current rows limit +abstract public **getPaginate** () inherited from :doc:`Phalcon\\Paginator\\AdapterInterface ` + +... + + diff --git a/zh/api/Phalcon_Paginator_Adapter_Model.rst b/zh/api/Phalcon_Paginator_Adapter_Model.rst index 7c8406fe271f..d54a4362c7f0 100644 --- a/zh/api/Phalcon_Paginator_Adapter_Model.rst +++ b/zh/api/Phalcon_Paginator_Adapter_Model.rst @@ -10,23 +10,23 @@ Class **Phalcon\\Paginator\\Adapter\\Model** :raw-html:`Source on GitHub` -This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. +This adapter allows to paginate data using a Phalcon\\Mvc\\Model resultset as a base. .. code-block:: php Robots::find(), - 'limit' => 25, - 'page' => $currentPage - ] - ); - - $paginate = $paginator->getPaginate(); + use Phalcon\Paginator\Adapter\Model; + + $paginator = new Model( + [ + "data" => Robots::find(), + "limit" => 25, + "page" => $currentPage, + ] + ); + + $paginate = $paginator->getPaginate(); diff --git a/zh/api/Phalcon_Paginator_Adapter_NativeArray.rst b/zh/api/Phalcon_Paginator_Adapter_NativeArray.rst index 301d2751e681..a1a8b8564fbe 100644 --- a/zh/api/Phalcon_Paginator_Adapter_NativeArray.rst +++ b/zh/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -10,27 +10,27 @@ Class **Phalcon\\Paginator\\Adapter\\NativeArray** :raw-html:`Source on GitHub` -Pagination using a PHP array as source of data +Pagination using a PHP array as source of data .. code-block:: php array( - ['id' => 1, 'name' => 'Artichoke'], - ['id' => 2, 'name' => 'Carrots'], - ['id' => 3, 'name' => 'Beet'], - ['id' => 4, 'name' => 'Lettuce'], - ['id' => 5, 'name' => ''] - ], - 'limit' => 2, - 'page' => $currentPage, - ] - ); + use Phalcon\Paginator\Adapter\NativeArray; + + $paginator = new NativeArray( + [ + "data" => [ + ["id" => 1, "name" => "Artichoke"], + ["id" => 2, "name" => "Carrots"], + ["id" => 3, "name" => "Beet"], + ["id" => 4, "name" => "Lettuce"], + ["id" => 5, "name" => ""], + ], + "limit" => 2, + "page" => $currentPage, + ] + ); diff --git a/zh/api/Phalcon_Paginator_Adapter_QueryBuilder.rst b/zh/api/Phalcon_Paginator_Adapter_QueryBuilder.rst index 66b206b5dbfa..2711f0e64f59 100644 --- a/zh/api/Phalcon_Paginator_Adapter_QueryBuilder.rst +++ b/zh/api/Phalcon_Paginator_Adapter_QueryBuilder.rst @@ -10,26 +10,26 @@ Class **Phalcon\\Paginator\\Adapter\\QueryBuilder** :raw-html:`Source on GitHub` -Pagination using a PHQL query builder as source of data +Pagination using a PHQL query builder as source of data .. code-block:: php modelsManager->createBuilder() - ->columns('id, name') - ->from('Robots') - ->orderBy('name'); - - $paginator = new QueryBuilder( - [ - 'builder' => $builder, - 'limit' => 20, - 'page' => 1, - ] - ); + use Phalcon\Paginator\Adapter\QueryBuilder; + + $builder = $this->modelsManager->createBuilder() + ->columns("id, name") + ->from("Robots") + ->orderBy("name"); + + $paginator = new QueryBuilder( + [ + "builder" => $builder, + "limit" => 20, + "page" => 1, + ] + ); diff --git a/zh/api/Phalcon_Queue_Beanstalk.rst b/zh/api/Phalcon_Queue_Beanstalk.rst index a942ababcc51..414a1cf4bf0d 100644 --- a/zh/api/Phalcon_Queue_Beanstalk.rst +++ b/zh/api/Phalcon_Queue_Beanstalk.rst @@ -6,19 +6,22 @@ Class **Phalcon\\Queue\\Beanstalk** :raw-html:`Source on GitHub` -Class to access the beanstalk queue service. Partially implements the protocol version 1.2 +Class to access the beanstalk queue service. +Partially implements the protocol version 1.2 .. code-block:: php '127.0.0.1', - 'port' => 11300, - 'persistent' => true, - ]); + use Phalcon\Queue\Beanstalk; + + $queue = new Beanstalk( + [ + "host" => "127.0.0.1", + "port" => 11300, + "persistent" => true, + ] + ); @@ -40,7 +43,7 @@ Constants Methods ------- -public **__construct** ([*array* $options]) +public **__construct** ([*array* $parameters]) @@ -162,7 +165,8 @@ Fetch a YAML payload from the Beanstalkd server public **read** ([*mixed* $length]) -Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection. +Reads a packet from the socket. Prior to reading from the socket will +check for availability of the connection. diff --git a/zh/api/Phalcon_Queue_Beanstalk_Job.rst b/zh/api/Phalcon_Queue_Beanstalk_Job.rst index 12d196fd9c70..31155c5319ea 100644 --- a/zh/api/Phalcon_Queue_Beanstalk_Job.rst +++ b/zh/api/Phalcon_Queue_Beanstalk_Job.rst @@ -38,19 +38,28 @@ Removes a job from the server entirely public **release** ([*mixed* $priority], [*mixed* $delay]) -The release command puts a reserved job back into the ready queue (and marks its state as "ready") to be run by any client. It is normally used when the job fails because of a transitory error. +The release command puts a reserved job back into the ready queue (and marks +its state as "ready") to be run by any client. It is normally used when the job +fails because of a transitory error. public **bury** ([*mixed* $priority]) -The bury command puts a job into the "buried" state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the "kick" command. +The bury command puts a job into the "buried" state. Buried jobs are put into +a FIFO linked list and will not be touched by the server again until a client +kicks them with the "kick" command. public **touch** () -The `touch` command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it's still alive and processing a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued. +The `touch` command allows a worker to request more time to work on a job. +This is useful for jobs that potentially take a long time, but you still +want the benefits of a TTR pulling a job away from an unresponsive worker. +A worker may periodically tell the server that it's still alive and processing +a job (e.g. it may do this on `DEADLINE_SOON`). The command postpones the auto +release of a reserved job until TTR seconds from when the command is issued. diff --git a/zh/api/Phalcon_Registry.rst b/zh/api/Phalcon_Registry.rst index a904f29e3bb0..54e09abfb7fa 100644 --- a/zh/api/Phalcon_Registry.rst +++ b/zh/api/Phalcon_Registry.rst @@ -8,35 +8,54 @@ Final class **Phalcon\\Registry** :raw-html:`Source on GitHub` -A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. +A registry is a container for storing objects and values in the application space. +By storing the value in a registry, the same object is always available throughout +your application. .. code-block:: php something = 'something'; - // or - $registry['something'] = 'something'; - - // Get value - $value = $registry->something; - // or - $value = $registry['something']; - - // Check if the key exists - $exists = isset($registry->something); - // or - $exists = isset($registry['something']); - - // Unset - unset($registry->something); - // or - unset($registry['something']); - - In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented. Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from. Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property. Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls. + $registry = new \Phalcon\Registry(); + + // Set value + $registry->something = "something"; + // or + $registry["something"] = "something"; + + // Get value + $value = $registry->something; + // or + $value = $registry["something"]; + + // Check if the key exists + $exists = isset($registry->something); + // or + $exists = isset($registry["something"]); + + // Unset + unset($registry->something); + // or + unset($registry["something"]); + +In addition to ArrayAccess, Phalcon\\Registry also implements Countable +(count($registry) will return the number of elements in the registry), +Serializable and Iterator (you can iterate over the registry +using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable +interface is implemented. + +Phalcon\\Registry is very fast (it is typically faster than any userspace +implementation of the registry); however, this comes at a price: +Phalcon\\Registry is a final class and cannot be inherited from. + +Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, +it is not recommended to invoke them manually (these methods exist mainly to +match the interfaces the registry implements): $registry->__get("property") +is several times slower than $registry->property. + +Internally all the magic methods (and interfaces except JsonSerializable) +are implemented using object handlers or similar techniques: this allows +to bypass relatively slow method calls. Methods diff --git a/zh/api/Phalcon_Security.rst b/zh/api/Phalcon_Security.rst index 2b70bd958e86..5b74d5040df4 100644 --- a/zh/api/Phalcon_Security.rst +++ b/zh/api/Phalcon_Security.rst @@ -8,20 +8,21 @@ Class **Phalcon\\Security** :raw-html:`Source on GitHub` -This component provides a set of functions to improve the security in Phalcon applications +This component provides a set of functions to improve the security in Phalcon applications .. code-block:: php request->getPost('login'); - $password = $this->request->getPost('password'); - + $login = $this->request->getPost("login"); + $password = $this->request->getPost("password"); + $user = Users::findFirstByLogin($login); + if ($user) { - if ($this->security->checkHash($password, $user->password)) { - //The password is valid - } + if ($this->security->checkHash($password, $user->password)) { + // The password is valid + } } @@ -178,15 +179,16 @@ Testing for LibreSSL public **getSslVersionNumber** () -Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. +Getting OpenSSL or LibreSSL version +Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. .. code-block:: php getSslVersionNumber() >= 20105) { - // ... - } + if ($security->getSslVersionNumber() >= 20105) { + // ... + } diff --git a/zh/api/Phalcon_Security_Random.rst b/zh/api/Phalcon_Security_Random.rst index 8656c705ef2d..5289cec81a64 100644 --- a/zh/api/Phalcon_Security_Random.rst +++ b/zh/api/Phalcon_Security_Random.rst @@ -6,55 +6,71 @@ Class **Phalcon\\Security\\Random** :raw-html:`Source on GitHub` -Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom `Phalcon\\Security\\Random` could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems +Secure random number generator class. + +Provides secure random number generator which is suitable for generating +session key in HTTP cookies, etc. + +It supports following secure random number generators: + +- random_bytes (PHP 7) +- libsodium +- openssl, libressl +- /dev/urandom + +`Phalcon\\Security\\Random` could be mainly useful for: + +- Key generation (e.g. generation of complicated keys) +- Generating random passwords for new user accounts +- Encryption systems .. code-block:: php bytes(); - - // Random hex string - echo $random->hex(10); // a29f470508d5ccb8e289 - echo $random->hex(10); // 533c2f08d5eee750e64a - echo $random->hex(11); // f362ef96cb9ffef150c9cd - echo $random->hex(12); // 95469d667475125208be45c4 - echo $random->hex(13); // 05475e8af4a34f8f743ab48761 - - // Random base64 string - echo $random->base64(12); // XfIN81jGGuKkcE1E - echo $random->base64(12); // 3rcq39QzGK9fUqh8 - echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== - echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== - - // Random URL-safe base64 string - echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA - echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug - echo $random->base64Safe(8); // mGyy0evy3ok - echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== - - // Random UUID - echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 - echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 - echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 - echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d - - // Random number between 0 and $len - echo $random->number(256); // 84 - echo $random->number(256); // 79 - echo $random->number(100); // 29 - echo $random->number(300); // 40 - - // Random base58 string - echo $random->base58(); // 4kUgL2pdQMSCQtjE - echo $random->base58(); // Umjxqf7ZPwh765yR - echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 - echo $random->base58(7); // 774SJD3vgP - - This class partially borrows SecureRandom library from Ruby + $random = new \Phalcon\Security\Random(); + + // Random binary string + $bytes = $random->bytes(); + + // Random hex string + echo $random->hex(10); // a29f470508d5ccb8e289 + echo $random->hex(10); // 533c2f08d5eee750e64a + echo $random->hex(11); // f362ef96cb9ffef150c9cd + echo $random->hex(12); // 95469d667475125208be45c4 + echo $random->hex(13); // 05475e8af4a34f8f743ab48761 + + // Random base64 string + echo $random->base64(12); // XfIN81jGGuKkcE1E + echo $random->base64(12); // 3rcq39QzGK9fUqh8 + echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ== + echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg== + + // Random URL-safe base64 string + echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug + echo $random->base64Safe(8); // mGyy0evy3ok + echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ== + + // Random UUID + echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235 + echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2 + echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9 + echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d + + // Random number between 0 and $len + echo $random->number(256); // 84 + echo $random->number(256); // 79 + echo $random->number(100); // 29 + echo $random->number(300); // 40 + + // Random base58 string + echo $random->base58(); // 4kUgL2pdQMSCQtjE + echo $random->base58(); // Umjxqf7ZPwh765yR + echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9 + echo $random->base58(7); // 774SJD3vgP + +This class partially borrows SecureRandom library from Ruby Methods @@ -62,107 +78,132 @@ Methods public **bytes** ([*mixed* $len]) -Generates a random binary string The `Random::bytes` method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: "x00" - "xFF". +Generates a random binary string +The `Random::bytes` method returns a string and accepts as input an int +representing the length in bytes to be returned. +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain any byte: "x00" - "xFF". .. code-block:: php bytes(); - var_dump(bin2hex($bytes)); - // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" + $random = new \Phalcon\Security\Random(); + + $bytes = $random->bytes(); + var_dump(bin2hex($bytes)); + // Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee" public **hex** ([*mixed* $len]) -Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. +Generates a random hex string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. .. code-block:: php hex(10); // a29f470508d5ccb8e289 + $random = new \Phalcon\Security\Random(); + + echo $random->hex(10); // a29f470508d5ccb8e289 public **base58** ([*mixed* $n]) -Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed. +Generates a random base58 string +If $len is not specified, 16 is assumed. It may be larger in future. +The result may contain alphanumeric characters except 0, O, I and l. +It is similar to Base64 but has been modified to avoid both non-alphanumeric +characters and letters which might look ambiguous when printed. .. code-block:: php base58(); // 4kUgL2pdQMSCQtjE + $random = new \Phalcon\Security\Random(); + + echo $random->base58(); // 4kUgL2pdQMSCQtjE public **base64** ([*mixed* $len]) -Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. +Generates a random base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4. .. code-block:: php base64(12); // 3rcq39QzGK9fUqh8 + $random = new \Phalcon\Security\Random(); + + echo $random->base64(12); // 3rcq39QzGK9fUqh8 public **base64Safe** ([*mixed* $len], [*mixed* $padding]) -Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because "=" may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64. +Generates a random URL-safe base64 string +If $len is not specified, 16 is assumed. It may be larger in future. +The length of the result string is usually greater of $len. +By default, padding is not generated because "=" may be used as a URL delimiter. +The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true. +See RFC 3548 for the definition of URL-safe base64. .. code-block:: php base64Safe(); // GD8JojhzSTrqX7Q8J6uug + $random = new \Phalcon\Security\Random(); + + echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug public **uuid** () -Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn't contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). +Generates a v4 random UUID (Universally Unique IDentifier) +The version 4 UUID is purely random (except the version). It doesn't contain meaningful +information such as MAC address, time, etc. See RFC 4122 for details of UUID. +This algorithm sets the version number (4 bits) as well as two reserved bits. +All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. +Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal +digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479). .. code-block:: php uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 + $random = new \Phalcon\Security\Random(); + + echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22 public **number** (*mixed* $len) -Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len. +Generates a random number between 0 and $len +Returns an integer: 0 <= result <= $len. .. code-block:: php number(16); // 8 + $random = new \Phalcon\Security\Random(); + + echo $random->number(16); // 8 diff --git a/zh/api/Phalcon_Session_Adapter.rst b/zh/api/Phalcon_Session_Adapter.rst index 616d792218ff..68b87f40cbe6 100644 --- a/zh/api/Phalcon_Session_Adapter.rst +++ b/zh/api/Phalcon_Session_Adapter.rst @@ -37,13 +37,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -74,59 +78,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () -Returns active session id +Returns active session id .. code-block:: php @@ -139,7 +145,7 @@ Returns active session id public **setId** (*mixed* $id) -Set the current session id +Set the current session id .. code-block:: php @@ -152,44 +158,53 @@ Set the current session id public **isStarted** () -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/zh/api/Phalcon_Session_Adapter_Files.rst b/zh/api/Phalcon_Session_Adapter_Files.rst index af65c1389000..995066a01e5a 100644 --- a/zh/api/Phalcon_Session_Adapter_Files.rst +++ b/zh/api/Phalcon_Session_Adapter_Files.rst @@ -36,13 +36,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -73,59 +77,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -138,7 +144,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -151,44 +157,53 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **destroy** ([*mixed* $removeData]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Destroys the active session +Destroys the active session .. code-block:: php destroy()); - var_dump($session->destroy(true)); + var_dump( + $session->destroy() + ); + + var_dump( + $session->destroy(true) + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/zh/api/Phalcon_Session_Adapter_Libmemcached.rst b/zh/api/Phalcon_Session_Adapter_Libmemcached.rst index 1be294d7bf57..b0b7790abf6a 100644 --- a/zh/api/Phalcon_Session_Adapter_Libmemcached.rst +++ b/zh/api/Phalcon_Session_Adapter_Libmemcached.rst @@ -10,31 +10,37 @@ Class **Phalcon\\Session\\Adapter\\Libmemcached** :raw-html:`Source on GitHub` -This adapter store sessions in libmemcached +This adapter store sessions in libmemcached .. code-block:: php [ - ['host' => 'localhost', 'port' => 11211, 'weight' => 1], - ], - 'client' => [ - \Memcached::OPT_HASH => \Memcached::HASH_MD5, - \Memcached::OPT_PREFIX_KEY => 'prefix.', - ], - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Libmemcached; + + $session = new Libmemcached( + [ + "servers" => [ + [ + "host" => "localhost", + "port" => 11211, + "weight" => 1, + ], + ], + "client" => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => "prefix.", + ], + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -108,13 +114,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -145,59 +155,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -210,7 +222,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -223,30 +235,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/zh/api/Phalcon_Session_Adapter_Memcache.rst b/zh/api/Phalcon_Session_Adapter_Memcache.rst index 82a7f34671da..51beaa623918 100644 --- a/zh/api/Phalcon_Session_Adapter_Memcache.rst +++ b/zh/api/Phalcon_Session_Adapter_Memcache.rst @@ -10,28 +10,30 @@ Class **Phalcon\\Session\\Adapter\\Memcache** :raw-html:`Source on GitHub` -This adapter store sessions in memcache +This adapter store sessions in memcache .. code-block:: php 'my-private-app', - 'host' => '127.0.0.1', - 'port' => 11211, - 'persistent' => true, - 'lifetime' => 3600, - 'prefix' => 'my_' - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Memcache; + + $session = new Memcache( + [ + "uniqueId" => "my-private-app", + "host" => "127.0.0.1", + "port" => 11211, + "persistent" => true, + "lifetime" => 3600, + "prefix" => "my_", + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -105,13 +107,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -142,59 +148,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -207,7 +215,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -220,30 +228,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/zh/api/Phalcon_Session_Adapter_Redis.rst b/zh/api/Phalcon_Session_Adapter_Redis.rst index 3986f7dbc9d1..af5fb3cd31a9 100644 --- a/zh/api/Phalcon_Session_Adapter_Redis.rst +++ b/zh/api/Phalcon_Session_Adapter_Redis.rst @@ -10,30 +10,32 @@ Class **Phalcon\\Session\\Adapter\\Redis** :raw-html:`Source on GitHub` -This adapter store sessions in Redis +This adapter store sessions in Redis .. code-block:: php 'my-private-app', - 'host' => 'localhost', - 'port' => 6379, - 'auth' => 'foobared', - 'persistent' => false, - 'lifetime' => 3600, - 'prefix' => 'my_' - 'index' => 1, - ]); - - $session->start(); - - $session->set('var', 'some-value'); - - echo $session->get('var'); + use Phalcon\Session\Adapter\Redis; + + $session = new Redis( + [ + "uniqueId" => "my-private-app", + "host" => "localhost", + "port" => 6379, + "auth" => "foobared", + "persistent" => false, + "lifetime" => 3600, + "prefix" => "my", + "index" => 1, + ] + ); + + $session->start(); + + $session->set("var", "some-value"); + + echo $session->get("var"); @@ -109,13 +111,17 @@ Starts the session (if headers are already sent the session will not be started) public **setOptions** (*array* $options) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets session's options +Sets session's options .. code-block:: php setOptions(['uniqueId' => 'my-private-app']); + $session->setOptions( + [ + "uniqueId" => "my-private-app", + ] + ); @@ -146,59 +152,61 @@ public **regenerateId** ([*mixed* $deleteOldSession]) inherited from :doc:`Phal public **get** (*mixed* $index, [*mixed* $defaultValue], [*mixed* $remove]) inherited from :doc:`Phalcon\\Session\\Adapter ` -Gets a session variable from an application context +Gets a session variable from an application context .. code-block:: php get('auth', 'yes'); + $session->get("auth", "yes"); public **set** (*mixed* $index, *mixed* $value) inherited from :doc:`Phalcon\\Session\\Adapter ` -Sets a session variable in an application context +Sets a session variable in an application context .. code-block:: php set('auth', 'yes'); + $session->set("auth", "yes"); public **has** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether a session variable is set in an application context +Check whether a session variable is set in an application context .. code-block:: php has('auth')); + var_dump( + $session->has("auth") + ); public **remove** (*mixed* $index) inherited from :doc:`Phalcon\\Session\\Adapter ` -Removes a session variable from an application context +Removes a session variable from an application context .. code-block:: php remove('auth'); + $session->remove("auth"); public **getId** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns active session id +Returns active session id .. code-block:: php @@ -211,7 +219,7 @@ Returns active session id public **setId** (*mixed* $id) inherited from :doc:`Phalcon\\Session\\Adapter ` -Set the current session id +Set the current session id .. code-block:: php @@ -224,30 +232,34 @@ Set the current session id public **isStarted** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Check whether the session has been started +Check whether the session has been started .. code-block:: php isStarted()); + var_dump( + $session->isStarted() + ); public **status** () inherited from :doc:`Phalcon\\Session\\Adapter ` -Returns the status of the current session. +Returns the status of the current session. .. code-block:: php status()); - - if ($session->status() !== $session::SESSION_ACTIVE) { - $session->start(); - } + var_dump( + $session->status() + ); + + if ($session->status() !== $session::SESSION_ACTIVE) { + $session->start(); + } diff --git a/zh/api/Phalcon_Session_Bag.rst b/zh/api/Phalcon_Session_Bag.rst index ae4c8dea58f0..24c4fe567a2a 100644 --- a/zh/api/Phalcon_Session_Bag.rst +++ b/zh/api/Phalcon_Session_Bag.rst @@ -8,13 +8,15 @@ Class **Phalcon\\Session\\Bag** :raw-html:`Source on GitHub` -This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application +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; @@ -43,136 +45,141 @@ 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 accessed +Initializes the session bag. This method must not be called directly, the +class calls it when its internal data is accessed public **destroy** () -Destroys the session bag +Destroys the session bag .. code-block:: php destroy(); + $user->destroy(); public **set** (*mixed* $property, *mixed* $value) -Sets a value in the session bag +Sets a value in the session bag .. code-block:: php set('name', 'Kimbra'); + $user->set("name", "Kimbra"); public **__set** (*mixed* $property, *mixed* $value) -Magic setter to assign values to the session bag +Magic setter to assign values to the session bag .. code-block:: php name = "Kimbra"; + $user->name = "Kimbra"; public **get** (*mixed* $property, [*mixed* $defaultValue]) -Obtains a value from the session bag optionally setting a default value +Obtains a value from the session bag optionally setting a default value .. code-block:: php get('name', 'Kimbra'); + echo $user->get("name", "Kimbra"); public **__get** (*mixed* $property) -Magic getter to obtain values from the session bag +Magic getter to obtain values from the session bag .. code-block:: php name; + echo $user->name; public **has** (*mixed* $property) -Check whether a property is defined in the internal bag +Check whether a property is defined in the internal bag .. code-block:: php has('name')); + var_dump( + $user->has("name") + ); public **__isset** (*mixed* $property) -Magic isset to check whether a property is defined in the bag +Magic isset to check whether a property is defined in the bag .. code-block:: php remove('name'); + $user->remove("name"); public **__unset** (*mixed* $property) -Magic unset to remove items using the array syntax +Magic unset to remove items using the array syntax .. code-block:: php count(); + echo $user->count(); diff --git a/zh/api/Phalcon_Tag.rst b/zh/api/Phalcon_Tag.rst index 0c36bcafb8f3..290bc1c76919 100644 --- a/zh/api/Phalcon_Tag.rst +++ b/zh/api/Phalcon_Tag.rst @@ -6,7 +6,9 @@ Class **Phalcon\\Tag** :raw-html:`Source on GitHub` -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. +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 @@ -81,34 +83,38 @@ Set autoescape mode in generated html public static **setDefault** (*string* $id, *string* $value) -Assigns default values to generated tags by helpers +Assigns default values to generated tags by helpers .. code-block:: php "peter")); - - // Later in the view - echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default + // Assigning "peter" to "name" component + Phalcon\Tag::setDefaults( + [ + "name" => "peter", + ] + ); + + // Later in the view + echo Phalcon\Tag::textField("name"); // Will have the value "peter" by default @@ -121,36 +127,74 @@ Alias of Phalcon\\Tag::setDefault public static *boolean* **hasValue** (*string* $name) -Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from _POST +Check if a helper has a default value set using Phalcon\\Tag::setDefault or value from $_POST public static *mixed* **getValue** (*string* $name, [*array* $params]) -Every helper calls this function to check whether a component has a predefined value using Phalcon\\Tag::setDefault or value from _POST +Every helper calls this function to check whether a component has a predefined +value using Phalcon\\Tag::setDefault or value from $_POST public static **resetInput** () -Resets the request and internal values to avoid those fields will have any default value +Resets the request and internal values to avoid those fields will have any default value. -public static *string* **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) +public static **linkTo** (*array* | *string* $parameters, [*string* $text], [*boolean* $local]) -Builds a HTML A tag using framework conventions +Builds a HTML A tag using framework conventions .. code-block:: php "btn-primary")); - echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE)); - echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE)); + echo Phalcon\Tag::linkTo("signup/register", "Register Here!"); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!" + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "signup/register", + "Register Here!", + "class" => "btn-primary", + ] + ); + + echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "http://phalconphp.com/", + "Phalcon Home", + "local" => false, + ] + ); + + echo Phalcon\Tag::linkTo( + [ + "action" => "http://phalconphp.com/", + "text" => "Phalcon Home", + "local" => false, + "target" => "_new" + ] + ); @@ -175,26 +219,37 @@ Builds a HTML input[type="color"] tag public static *string* **textField** (*array* $parameters) -Builds a HTML input[type="text"] tag +Builds a HTML input[type="text"] tag .. code-block:: php 30)); + echo Phalcon\Tag::textField( + [ + "name", + "size" => 30, + ] + ); public static *string* **numericField** (*array* $parameters) -Builds a HTML input[type="number"] tag +Builds a HTML input[type="number"] tag .. code-block:: php "1", "max" => "5")); + echo Phalcon\Tag::numericField( + [ + "price", + "min" => "1", + "max" => "5", + ] + ); @@ -207,26 +262,31 @@ Builds a HTML input[type="range"] tag public static *string* **emailField** (*array* $parameters) -Builds a HTML input[type="email"] tag +Builds a HTML input[type="email"] tag .. code-block:: php "14-12-1980")) + echo Phalcon\Tag::dateField( + [ + "born", + "value" => "14-12-1980", + ] + ); @@ -263,39 +323,49 @@ Builds a HTML input[type="week"] tag public static *string* **passwordField** (*array* $parameters) -Builds a HTML input[type="password"] tag +Builds a HTML input[type="password"] tag .. code-block:: php 30)); + echo Phalcon\Tag::passwordField( + [ + "name", + "size" => 30, + ] + ); public static *string* **hiddenField** (*array* $parameters) -Builds a HTML input[type="hidden"] tag +Builds a HTML input[type="hidden"] tag .. code-block:: php "mike")); + echo Phalcon\Tag::hiddenField( + [ + "name", + "value" => "mike", + ] + ); public static *string* **fileField** (*array* $parameters) -Builds a HTML input[type="file"] tag +Builds a HTML input[type="file"] tag .. code-block:: php "Y")); + echo Phalcon\Tag::checkField( + [ + "terms", + "value" => "Y", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "hot")) + echo Phalcon\Tag::radioField( + [ + "weather", + "value" => "hot", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "/img/button.png")); + echo Phalcon\Tag::imageInput( + [ + "src" => "/img/button.png", + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "Active", "I" => "Inactive")) + echo Phalcon\Tag::selectStatic( + "status", + [ + "A" => "Active", + "I" => "Inactive", + ] + ); public static *string* **select** (*array* $parameters, [*array* $data]) -Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options +Builds a HTML SELECT tag using a Phalcon\\Mvc\\Model resultset as options .. code-block:: php ["id", "name"] - ]); + echo Phalcon\Tag::select( + [ + "robotId", + Robots::find("type = "mechanical""), + "using" => ["id", "name"], + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php 10, "rows" => 4)) + echo Phalcon\Tag::textArea( + [ + "comments", + "cols" => 10, + "rows" => 4, + ] + ); -Volt syntax: +Volt syntax: .. code-block:: php "post")); + echo Phalcon\Tag::form("posts/save"); -Volt syntax: + echo Phalcon\Tag::form( + [ + "posts/save", + "method" => "post", + ] + ); + +Volt syntax: .. code-block:: php "Some Photo")); + echo Phalcon\Tag::image("img/bg.png"); + + echo Phalcon\Tag::image( + [ + "img/photo.jpg", + "alt" => "Some Photo", + ] + ); -Volt Syntax: +Volt Syntax: .. code-block:: php ` + .. role:: raw-html(raw) :format: html @@ -64,3 +66,13 @@ Replaces placeholders by the values passed +abstract public **query** (*mixed* $index, [*mixed* $placeholders]) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + +abstract public **exists** (*mixed* $index) inherited from :doc:`Phalcon\\Translate\\AdapterInterface ` + +... + + diff --git a/zh/api/Phalcon_Translate_Adapter_Gettext.rst b/zh/api/Phalcon_Translate_Adapter_Gettext.rst index cd57b4fb0cc8..5bd812493fdf 100644 --- a/zh/api/Phalcon_Translate_Adapter_Gettext.rst +++ b/zh/api/Phalcon_Translate_Adapter_Gettext.rst @@ -10,6 +10,22 @@ Class **Phalcon\\Translate\\Adapter\\Gettext** :raw-html:`Source on GitHub` + +.. code-block:: php + + "de_DE.UTF-8", + "defaultDomain" => "translations", + "directory" => "/path/to/application/locales", + "category" => LC_MESSAGES, + ] + ); + Allows translate using gettext @@ -46,9 +62,16 @@ Phalcon\\Translate\\Adapter\\Gettext constructor -public *string* **query** (*string* $index, [*array* $placeholders]) +public **query** (*mixed* $index, [*mixed* $placeholders]) + +Returns the translation related to the given key. + +.. code-block:: php + + query("你好 %name%!", ["name" => "Phalcon"]); -Returns the translation related to the given key @@ -60,7 +83,8 @@ Check whether is defined a translation key in the internal array public **nquery** (*mixed* $msgid1, *mixed* $msgid2, *mixed* $count, [*mixed* $placeholders], [*mixed* $domain]) -The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count. +The plural version of gettext(). +Some languages have more than one form for plural messages dependent on the count. @@ -84,37 +108,39 @@ Sets the domain default to search within when calls are made to gettext() public **setDirectory** (*mixed* $directory) -Sets the path for a domain +Sets the path for a domain .. code-block:: php setDirectory('/path/to/the/messages'); - - // Set the domains and directories path - $gettext->setDirectory([ - 'messages' => '/path/to/the/messages', - 'another' => '/path/to/the/another' - ]); + // Set the directory path + $gettext->setDirectory("/path/to/the/messages"); + + // Set the domains and directories path + $gettext->setDirectory( + [ + "messages" => "/path/to/the/messages", + "another" => "/path/to/the/another", + ] + ); public **setLocale** (*mixed* $category, *mixed* $locale) -Sets locale information +Sets locale information .. code-block:: php setLocale(LC_ALL, 'nl_NL'); - - // Try different possible locale names for german - $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge'); + // Set locale to Dutch + $gettext->setLocale(LC_ALL, "nl_NL"); + + // Try different possible locale names for german + $gettext->setLocale(LC_ALL, "de_DE@euro", "de_DE", "de", "ge"); diff --git a/zh/api/Phalcon_Validation.rst b/zh/api/Phalcon_Validation.rst index 3f76208c82df..638c13b95de0 100644 --- a/zh/api/Phalcon_Validation.rst +++ b/zh/api/Phalcon_Validation.rst @@ -119,7 +119,8 @@ Appends a message to the messages list public :doc:`Phalcon\\Validation ` **bind** (*object* $entity, *array* | *object* $data) -Assigns the data to an entity The entity is used to obtain the validation values +Assigns the data to an entity +The entity is used to obtain the validation values diff --git a/zh/api/Phalcon_Validation_CombinedFieldsValidator.rst b/zh/api/Phalcon_Validation_CombinedFieldsValidator.rst index ee9878f0ba81..6010bff80bbf 100644 --- a/zh/api/Phalcon_Validation_CombinedFieldsValidator.rst +++ b/zh/api/Phalcon_Validation_CombinedFieldsValidator.rst @@ -33,7 +33,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Message.rst b/zh/api/Phalcon_Validation_Message.rst index 57642482a1ff..328582f249a5 100644 --- a/zh/api/Phalcon_Validation_Message.rst +++ b/zh/api/Phalcon_Validation_Message.rst @@ -76,7 +76,7 @@ Magic __toString method returns verbose message public static **__set_state** (*array* $message) -Magic __set_state helps to recover messsages from serialization +Magic __set_state helps to recover messages from serialization diff --git a/zh/api/Phalcon_Validation_Message_Group.rst b/zh/api/Phalcon_Validation_Message_Group.rst index 4e120b57fe17..bf4e052a9269 100644 --- a/zh/api/Phalcon_Validation_Message_Group.rst +++ b/zh/api/Phalcon_Validation_Message_Group.rst @@ -22,78 +22,84 @@ Phalcon\\Validation\\Message\\Group constructor public :doc:`Phalcon\\Validation\\Message ` **offsetGet** (*int* $index) -Gets an attribute a message using the array syntax +Gets an attribute a message using the array syntax .. code-block:: php ` $message) -Sets an attribute using the array-syntax +Sets an attribute using the array-syntax .. code-block:: php ` $message) -Appends a message to the group +Appends a message to the group .. code-block:: php appendMessage(new \Phalcon\Validation\Message('This is a message')); + $messages->appendMessage( + new \Phalcon\Validation\Message("This is a message") + ); public **appendMessages** (:doc:`Phalcon\\Validation\\MessageInterface `\ [] $messages) -Appends an array of messages to the group +Appends an array of messages to the group .. code-block:: php appendMessages($messagesArray); + $messages->appendMessages($messagesArray); diff --git a/zh/api/Phalcon_Validation_Validator.rst b/zh/api/Phalcon_Validation_Validator.rst index 1520d3c6aa37..eb648911d80a 100644 --- a/zh/api/Phalcon_Validation_Validator.rst +++ b/zh/api/Phalcon_Validation_Validator.rst @@ -34,7 +34,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Alnum.rst b/zh/api/Phalcon_Validation_Validator_Alnum.rst index 9c0990f08c98..fade64b887b8 100644 --- a/zh/api/Phalcon_Validation_Validator_Alnum.rst +++ b/zh/api/Phalcon_Validation_Validator_Alnum.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alnum** :raw-html:`Source on GitHub` -Check for alphanumeric character(s) +Check for alphanumeric character(s) .. code-block:: php add('username', new AlnumValidator([ - 'message' => ':field must contain only alphanumeric characters' - ])); - - $validator->add(['username', 'name'], new AlnumValidator([ - 'message' => [ - 'username' => 'username must contain only alphanumeric characters', - 'name' => 'name must contain only alphanumeric characters' - ] - ])); + use Phalcon\Validation\Validator\Alnum as AlnumValidator; + + $validator->add( + "username", + new AlnumValidator( + [ + "message" => ":field must contain only alphanumeric characters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlnumValidator( + [ + "message" => [ + "username" => "username must contain only alphanumeric characters", + "name" => "name must contain only alphanumeric characters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Alpha.rst b/zh/api/Phalcon_Validation_Validator_Alpha.rst index 108ee7f80cd5..e9530ba13297 100644 --- a/zh/api/Phalcon_Validation_Validator_Alpha.rst +++ b/zh/api/Phalcon_Validation_Validator_Alpha.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Alpha** :raw-html:`Source on GitHub` -Check for alphabetic character(s) +Check for alphabetic character(s) .. code-block:: php add('username', new AlphaValidator([ - 'message' => ':field must contain only letters' - ])); - - $validator->add(['username', 'name'], new AlphaValidator([ - 'message' => [ - 'username' => 'username must contain only letters', - 'name' => 'name must contain only letters' - ] - ])); + use Phalcon\Validation\Validator\Alpha as AlphaValidator; + + $validator->add( + "username", + new AlphaValidator( + [ + "message" => ":field must contain only letters", + ] + ) + ); + + $validator->add( + [ + "username", + "name", + ], + new AlphaValidator( + [ + "message" => [ + "username" => "username must contain only letters", + "name" => "name must contain only letters", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Between.rst b/zh/api/Phalcon_Validation_Validator_Between.rst index 57ee0ae0ef01..3625ed44cd27 100644 --- a/zh/api/Phalcon_Validation_Validator_Between.rst +++ b/zh/api/Phalcon_Validation_Validator_Between.rst @@ -10,34 +10,48 @@ Class **Phalcon\\Validation\\Validator\\Between** :raw-html:`Source on GitHub` -Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum. +Validates that a value is between an inclusive range of two values. +For a value x, the test is passed if minimum<=x<=maximum. .. code-block:: php add('price', new Between([ - 'minimum' => 0, - 'maximum' => 100, - 'message' => 'The price must be between 0 and 100' - ])); - - $validator->add(['price', 'amount'], new Between([ - 'minimum' => [ - 'price' => 0, - 'amount' => 0 - ], - 'maximum' => [ - 'price' => 100, - 'amount' => 50 - ], - 'message' => [ - 'price' => 'The price must be between 0 and 100', - 'amount' => 'The amount must be between 0 and 50' - ] - ])); + use Phalcon\Validation\Validator\Between; + + $validator->add( + "price", + new Between( + [ + "minimum" => 0, + "maximum" => 100, + "message" => "The price must be between 0 and 100", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Between( + [ + "minimum" => [ + "price" => 0, + "amount" => 0, + ], + "maximum" => [ + "price" => 100, + "amount" => 50, + ], + "message" => [ + "price" => "The price must be between 0 and 100", + "amount" => "The amount must be between 0 and 50", + ], + ] + ) + ); @@ -70,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Confirmation.rst b/zh/api/Phalcon_Validation_Validator_Confirmation.rst index 5a79a2f4f668..5bb6ead06ca7 100644 --- a/zh/api/Phalcon_Validation_Validator_Confirmation.rst +++ b/zh/api/Phalcon_Validation_Validator_Confirmation.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Confirmation** :raw-html:`Source on GitHub` -Checks that two values have the same value +Checks that two values have the same value .. code-block:: php add('password', new Confirmation([ - 'message' => 'Password doesn\'t match confirmation', - 'with' => 'confirmPassword' - ])); - - $validator->add(['password', 'email'], new Confirmation([ - 'message' => [ - 'password' => 'Password doesn\'t match confirmation', - 'email' => 'Email doesn\'t match confirmation' - ], - 'with' => [ - 'password => 'confirmPassword', - 'email' => 'confirmEmail' - ] - ])); + use Phalcon\Validation\Validator\Confirmation; + + $validator->add( + "password", + new Confirmation( + [ + "message" => "Password doesn't match confirmation", + "with" => "confirmPassword", + ] + ) + ); + + $validator->add( + [ + "password", + "email", + ], + new Confirmation( + [ + "message" => [ + "password" => "Password doesn't match confirmation", + "email" => "Email doesn't match confirmation", + ], + "with" => [ + "password" => "confirmPassword", + "email" => "confirmEmail", + ], + ] + ) + ); @@ -71,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_CreditCard.rst b/zh/api/Phalcon_Validation_Validator_CreditCard.rst index 1ea77d868e3e..a18f8fed0142 100644 --- a/zh/api/Phalcon_Validation_Validator_CreditCard.rst +++ b/zh/api/Phalcon_Validation_Validator_CreditCard.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\CreditCard** :raw-html:`Source on GitHub` -Checks if a value has a valid credit card number +Checks if a value has a valid credit card number .. code-block:: php add('creditcard', new CreditCardValidator([ - 'message' => 'The credit card number is not valid' - ])); - - $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([ - 'message' => [ - 'creditcard' => 'The credit card number is not valid', - 'secondCreditCard' => 'The second credit card number is not valid' - ] - ])); + use Phalcon\Validation\Validator\CreditCard as CreditCardValidator; + + $validator->add( + "creditCard", + new CreditCardValidator( + [ + "message" => "The credit card number is not valid", + ] + ) + ); + + $validator->add( + [ + "creditCard", + "secondCreditCard", + ], + new CreditCardValidator( + [ + "message" => [ + "creditCard" => "The credit card number is not valid", + "secondCreditCard" => "The second credit card number is not valid", + ], + ] + ) + ); @@ -66,7 +79,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Date.rst b/zh/api/Phalcon_Validation_Validator_Date.rst index 84e4410d519b..779005e11bc4 100644 --- a/zh/api/Phalcon_Validation_Validator_Date.rst +++ b/zh/api/Phalcon_Validation_Validator_Date.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Date** :raw-html:`Source on GitHub` -Checks if a value is a valid date +Checks if a value is a valid date .. code-block:: php add('date', new DateValidator([ - 'format' => 'd-m-Y', - 'message' => 'The date is invalid' - ])); - - $validator->add(['date','anotherDate'], new DateValidator([ - 'format' => [ - 'date' => 'd-m-Y', - 'anotherDate' => 'Y-m-d' - ], - 'message' => [ - 'date' => 'The date is invalid', - 'anotherDate' => 'The another date is invalid' - ] - ])); + use Phalcon\Validation\Validator\Date as DateValidator; + + $validator->add( + "date", + new DateValidator( + [ + "format" => "d-m-Y", + "message" => "The date is invalid", + ] + ) + ); + + $validator->add( + [ + "date", + "anotherDate", + ], + new DateValidator( + [ + "format" => [ + "date" => "d-m-Y", + "anotherDate" => "Y-m-d", + ], + "message" => [ + "date" => "The date is invalid", + "anotherDate" => "The another date is invalid", + ], + ] + ) + ); @@ -70,7 +83,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Digit.rst b/zh/api/Phalcon_Validation_Validator_Digit.rst index b38d3f5c530b..d30741998908 100644 --- a/zh/api/Phalcon_Validation_Validator_Digit.rst +++ b/zh/api/Phalcon_Validation_Validator_Digit.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Digit** :raw-html:`Source on GitHub` -Check for numeric character(s) +Check for numeric character(s) .. code-block:: php add('height', new DigitValidator([ - 'message' => ':field must be numeric' - ])); - - $validator->add(['height', 'width'], new DigitValidator([ - 'message' => [ - 'height' => 'height must be numeric', - 'width' => 'width must be numeric' - ] - ])); + use Phalcon\Validation\Validator\Digit as DigitValidator; + + $validator->add( + "height", + new DigitValidator( + [ + "message" => ":field must be numeric", + ] + ) + ); + + $validator->add( + [ + "height", + "width", + ], + new DigitValidator( + [ + "message" => [ + "height" => "height must be numeric", + "width" => "width must be numeric", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Email.rst b/zh/api/Phalcon_Validation_Validator_Email.rst index 213e31296cce..07500eae1d6c 100644 --- a/zh/api/Phalcon_Validation_Validator_Email.rst +++ b/zh/api/Phalcon_Validation_Validator_Email.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Email** :raw-html:`Source on GitHub` -Checks if a value has a correct e-mail format +Checks if a value has a correct e-mail format .. code-block:: php add('email', new EmailValidator([ - 'message' => 'The e-mail is not valid' - ])); - - $validator->add(['email', 'anotherEmail'], new EmailValidator([ - 'message' => [ - 'email' => 'The e-mail is not valid', - 'anotherEmail' => 'The another e-mail is not valid' - ] - ])); + use Phalcon\Validation\Validator\Email as EmailValidator; + + $validator->add( + "email", + new EmailValidator( + [ + "message" => "The e-mail is not valid", + ] + ) + ); + + $validator->add( + [ + "email", + "anotherEmail", + ], + new EmailValidator( + [ + "message" => [ + "email" => "The e-mail is not valid", + "anotherEmail" => "The another e-mail is not valid", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_ExclusionIn.rst b/zh/api/Phalcon_Validation_Validator_ExclusionIn.rst index 123150d23ec2..9f18148886e6 100644 --- a/zh/api/Phalcon_Validation_Validator_ExclusionIn.rst +++ b/zh/api/Phalcon_Validation_Validator_ExclusionIn.rst @@ -10,29 +10,48 @@ Class **Phalcon\\Validation\\Validator\\ExclusionIn** :raw-html:`Source on GitHub` -Check if a value is not included into a list of values +Check if a value is not included into a list of values .. code-block:: php add('status', new ExclusionIn([ - 'message' => 'The status must not be A or B', - 'domain' => ['A', 'B'] - ])); - - $validator->add(['status', 'type'], new ExclusionIn([ - 'message' => [ - 'status' => 'The status must not be A or B', - 'type' => 'The type must not be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\ExclusionIn; + + $validator->add( + "status", + new ExclusionIn( + [ + "message" => "The status must not be A or B", + "domain" => [ + "A", + "B", + ], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new ExclusionIn( + [ + "message" => [ + "status" => "The status must not be A or B", + "type" => "The type must not be 1 or "' + ], + "domain" => [ + "status" => [ + "A", + "B", + ], + "type" => [1, 2], + ], + ] + ) + ); @@ -65,7 +84,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_File.rst b/zh/api/Phalcon_Validation_Validator_File.rst index 10fd1fd4b257..334d87acc235 100644 --- a/zh/api/Phalcon_Validation_Validator_File.rst +++ b/zh/api/Phalcon_Validation_Validator_File.rst @@ -10,48 +10,70 @@ Class **Phalcon\\Validation\\Validator\\File** :raw-html:`Source on GitHub` -Checks if a value has a correct file +Checks if a value has a correct file .. code-block:: php add('file', new FileValidator([ - 'maxSize' => '2M', - 'messageSize' => ':field exceeds the max filesize (:max)', - 'allowedTypes' => array('image/jpeg', 'image/png'), - 'messageType' => 'Allowed file types are :types', - 'maxResolution' => '800x600', - 'messageMaxResolution' => 'Max resolution of :field is :max' - ])); - - $validator->add(['file', 'anotherFile'], new FileValidator([ - 'maxSize' => [ - 'file' => '2M', - 'anotherFile' => '4M' - ], - 'messageSize' => [ - 'file' => 'file exceeds the max filesize 2M', - 'anotherFile' => 'anotherFile exceeds the max filesize 4M', - 'allowedTypes' => [ - 'file' => ['image/jpeg', 'image/png'], - 'anotherFile' => ['image/gif', 'image/bmp'] - ], - 'messageType' => [ - 'file' => 'Allowed file types are image/jpeg and image/png', - 'anotherFile' => 'Allowed file types are image/gif and image/bmp' - ], - 'maxResolution' => [ - 'file' => '800x600', - 'anotherFile' => '1024x768' - ], - 'messageMaxResolution' => [ - 'file' => 'Max resolution of file is 800x600', - 'anotherFile' => 'Max resolution of file is 1024x768' - ] - ])); + use Phalcon\Validation\Validator\File as FileValidator; + + $validator->add( + "file", + new FileValidator( + [ + "maxSize" => "2M", + "messageSize" => ":field exceeds the max filesize (:max)", + "allowedTypes" => [ + "image/jpeg", + "image/png", + ], + "messageType" => "Allowed file types are :types", + "maxResolution" => "800x600", + "messageMaxResolution" => "Max resolution of :field is :max", + ] + ) + ); + + $validator->add( + [ + "file", + "anotherFile", + ], + new FileValidator( + [ + "maxSize" => [ + "file" => "2M", + "anotherFile" => "4M", + ], + "messageSize" => [ + "file" => "file exceeds the max filesize 2M", + "anotherFile" => "anotherFile exceeds the max filesize 4M", + "allowedTypes" => [ + "file" => [ + "image/jpeg", + "image/png", + ], + "anotherFile" => [ + "image/gif", + "image/bmp", + ], + ], + "messageType" => [ + "file" => "Allowed file types are image/jpeg and image/png", + "anotherFile" => "Allowed file types are image/gif and image/bmp", + ], + "maxResolution" => [ + "file" => "800x600", + "anotherFile" => "1024x768", + ], + "messageMaxResolution" => [ + "file" => "Max resolution of file is 800x600", + "anotherFile" => "Max resolution of file is 1024x768", + ], + ] + ) + ); @@ -90,7 +112,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Identical.rst b/zh/api/Phalcon_Validation_Validator_Identical.rst index ae24af6029d6..67e967f6e598 100644 --- a/zh/api/Phalcon_Validation_Validator_Identical.rst +++ b/zh/api/Phalcon_Validation_Validator_Identical.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Identical** :raw-html:`Source on GitHub` -Checks if a value is identical to other +Checks if a value is identical to other .. code-block:: php add('terms', new Identical([ - 'accepted' => 'yes', - 'message' => 'Terms and conditions must be accepted' - ])); - - $validator->add(['terms', 'anotherTerms'], new Identical([ - 'accepted' => [ - 'terms' => 'yes', - 'anotherTerms' => 'yes' - ], - 'message' => [ - 'terms' => 'Terms and conditions must be accepted', - 'anotherTerms' => 'Another terms must be accepted' - ] - ])); + use Phalcon\Validation\Validator\Identical; + + $validator->add( + "terms", + new Identical( + [ + "accepted" => "yes", + "message" => "Terms and conditions must be accepted", + ] + ) + ); + + $validator->add( + [ + "terms", + "anotherTerms", + ], + new Identical( + [ + "accepted" => [ + "terms" => "yes", + "anotherTerms" => "yes", + ], + "message" => [ + "terms" => "Terms and conditions must be accepted", + "anotherTerms" => "Another terms must be accepted", + ], + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_InclusionIn.rst b/zh/api/Phalcon_Validation_Validator_InclusionIn.rst index 6de9d4955930..246932748da0 100644 --- a/zh/api/Phalcon_Validation_Validator_InclusionIn.rst +++ b/zh/api/Phalcon_Validation_Validator_InclusionIn.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\InclusionIn** :raw-html:`Source on GitHub` -Check if a value is included into a list of values +Check if a value is included into a list of values .. code-block:: php add('status', new InclusionIn([ - 'message' => 'The status must be A or B', - 'domain' => array('A', 'B') - ])); - - $validator->add(['status', 'type'], new InclusionIn([ - 'message' => [ - 'status' => 'The status must be A or B', - 'type' => 'The status must be 1 or 2' - ], - 'domain' => [ - 'status' => ['A', 'B'], - 'type' => [1, 2] - ] - ])); + use Phalcon\Validation\Validator\InclusionIn; + + $validator->add( + "status", + new InclusionIn( + [ + "message" => "The status must be A or B", + "domain" => ["A", "B"], + ] + ) + ); + + $validator->add( + [ + "status", + "type", + ], + new InclusionIn( + [ + "message" => [ + "status" => "The status must be A or B", + "type" => "The status must be 1 or 2", + ], + "domain" => [ + "status" => ["A", "B"], + "type" => [1, 2], + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Numericality.rst b/zh/api/Phalcon_Validation_Validator_Numericality.rst index c3b89244490f..df67fbce4d27 100644 --- a/zh/api/Phalcon_Validation_Validator_Numericality.rst +++ b/zh/api/Phalcon_Validation_Validator_Numericality.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Numericality** :raw-html:`Source on GitHub` -Check for a valid numeric value +Check for a valid numeric value .. code-block:: php add('price', new Numericality([ - 'message' => ':field is not numeric' - ])); - - $validator->add(['price', 'amount'], new Numericality([ - 'message' => [ - 'price' => 'price is not numeric', - 'amount' => 'amount is not numeric' - ] - ])); + use Phalcon\Validation\Validator\Numericality; + + $validator->add( + "price", + new Numericality( + [ + "message" => ":field is not numeric", + ] + ) + ); + + $validator->add( + [ + "price", + "amount", + ], + new Numericality( + [ + "message" => [ + "price" => "price is not numeric", + "amount" => "amount is not numeric", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_PresenceOf.rst b/zh/api/Phalcon_Validation_Validator_PresenceOf.rst index 5aa0122f7957..1d988586deae 100644 --- a/zh/api/Phalcon_Validation_Validator_PresenceOf.rst +++ b/zh/api/Phalcon_Validation_Validator_PresenceOf.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\PresenceOf** :raw-html:`Source on GitHub` -Validates that a value is not null or empty string +Validates that a value is not null or empty string .. code-block:: php add('name', new PresenceOf([ - 'message' => 'The name is required' - ])); - - $validator->add(['name', 'email'], new PresenceOf([ - 'message' => [ - 'name' => 'The name is required', - 'email' => 'The email is required' - ] - ])); + use Phalcon\Validation\Validator\PresenceOf; + + $validator->add( + "name", + new PresenceOf( + [ + "message" => "The name is required", + ] + ) + ); + + $validator->add( + [ + "name", + "email", + ], + new PresenceOf( + [ + "message" => [ + "name" => "The name is required", + "email" => "The email is required", + ], + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Regex.rst b/zh/api/Phalcon_Validation_Validator_Regex.rst index d63a5f30f7c7..602afb9732e5 100644 --- a/zh/api/Phalcon_Validation_Validator_Regex.rst +++ b/zh/api/Phalcon_Validation_Validator_Regex.rst @@ -10,29 +10,42 @@ Class **Phalcon\\Validation\\Validator\\Regex** :raw-html:`Source on GitHub` -Allows validate if the value of a field matches a regular expression +Allows validate if the value of a field matches a regular expression .. code-block:: php add('created_at', new RegexValidator([ - 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'message' => 'The creation date is invalid' - ])); - - $validator->add(['created_at', 'name'], new RegexValidator([ - 'pattern' => [ - 'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/', - 'name' => '/^[a-z]$/' - ], - 'message' => [ - 'created_at' => 'The creation date is invalid', - 'name' => ' 'The name is invalid' - ] - ])); + use Phalcon\Validation\Validator\Regex as RegexValidator; + + $validator->add( + "created_at", + new RegexValidator( + [ + "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "message" => "The creation date is invalid", + ] + ) + ); + + $validator->add( + [ + "created_at", + "name", + ], + new RegexValidator( + [ + "pattern" => [ + "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/", + "name" => "/^[a-z]$/", + ], + "message" => [ + "created_at" => "The creation date is invalid", + "name" => "The name is invalid", + ] + ] + ) + ); @@ -65,7 +78,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_StringLength.rst b/zh/api/Phalcon_Validation_Validator_StringLength.rst index ab9d0e812a5c..def48d04cd5f 100644 --- a/zh/api/Phalcon_Validation_Validator_StringLength.rst +++ b/zh/api/Phalcon_Validation_Validator_StringLength.rst @@ -10,39 +10,54 @@ Class **Phalcon\\Validation\\Validator\\StringLength** :raw-html:`Source on GitHub` -Validates that a string has the specified maximum and minimum constraints The test is passed if for a string's length L, min<=L<=max, i.e. L must be at least min, and at most max. +Validates that a string has the specified maximum and minimum constraints +The test is passed if for a string's length L, min<=L<=max, i.e. L must +be at least min, and at most max. .. code-block:: php add('name_last', new StringLength([ - 'max' => 50, - 'min' => 2, - 'messageMaximum' => 'We don\'t like really long names', - 'messageMinimum' => 'We want more than just their initials' - ])); - - $validation->add(['name_last', 'name_first'], new StringLength([ - 'max' => [ - 'name_last' => 50, - 'name_first' => 40 - ], - 'min' => [ - 'name_last' => 2, - 'name_first' => 4 - ], - 'messageMaximum' => [ - 'name_last' => 'We don\'t like really long last names', - 'name_first' => 'We don\'t like really long first names' - ], - 'messageMinimum' => [ - 'name_last' => 'We don\'t like too short last names', - 'name_first' => 'We don\'t like too short first names', - ] - ])); + use Phalcon\Validation\Validator\StringLength as StringLength; + + $validation->add( + "name_last", + new StringLength( + [ + "max" => 50, + "min" => 2, + "messageMaximum" => "We don't like really long names", + "messageMinimum" => "We want more than just their initials", + ] + ) + ); + + $validation->add( + [ + "name_last", + "name_first", + ], + new StringLength( + [ + "max" => [ + "name_last" => 50, + "name_first" => 40, + ], + "min" => [ + "name_last" => 2, + "name_first" => 4, + ], + "messageMaximum" => [ + "name_last" => "We don't like really long last names", + "name_first" => "We don't like really long first names", + ], + "messageMinimum" => [ + "name_last" => "We don't like too short last names", + "name_first" => "We don't like too short first names", + ] + ] + ) + ); @@ -75,7 +90,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Uniqueness.rst b/zh/api/Phalcon_Validation_Validator_Uniqueness.rst index af0bde58d45d..8af5174ddfba 100644 --- a/zh/api/Phalcon_Validation_Validator_Uniqueness.rst +++ b/zh/api/Phalcon_Validation_Validator_Uniqueness.rst @@ -10,59 +10,84 @@ Class **Phalcon\\Validation\\Validator\\Uniqueness** :raw-html:`Source on GitHub` -Check that a field is unique in the related table +Check that a field is unique in the related table .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'message' => ':field must be unique' - ])); + use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator; - Different attribute from the field: + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "message" => ":field must be unique", + ] + ) + ); + +Different attribute from the field: .. code-block:: php add('username', new UniquenessValidator([ - 'model' => new Users(), - 'attribute' => 'nick' - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "model" => new Users(), + "attribute" => "nick", + ] + ) + ); - In model: +In model: .. code-block:: php add('username', new UniquenessValidator()); + $validator->add( + "username", + new UniquenessValidator() + ); - Combination of fields in model: +Combination of fields in model: .. code-block:: php add(['firstName', 'lastName'], new UniquenessValidator()); + $validator->add( + [ + "firstName", + "lastName", + ], + new UniquenessValidator() + ); - It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup: +It is possible to convert values before validation. This is useful in +situations where values need to be converted to do the database lookup: .. code-block:: php add('username', new UniquenessValidator([ - 'convert' => function (array $values) { - $values['username'] = strtolower($values['username']); - - return $values; - } - ])); + $validator->add( + "username", + new UniquenessValidator( + [ + "convert" => function (array $values) { + $values["username"] = strtolower($values["username"]); + + return $values; + } + ] + ) + ); @@ -106,7 +131,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Validation_Validator_Url.rst b/zh/api/Phalcon_Validation_Validator_Url.rst index bc520e534f28..a032398e2b1b 100644 --- a/zh/api/Phalcon_Validation_Validator_Url.rst +++ b/zh/api/Phalcon_Validation_Validator_Url.rst @@ -10,24 +10,37 @@ Class **Phalcon\\Validation\\Validator\\Url** :raw-html:`Source on GitHub` -Checks if a value has a url format +Checks if a value has a url format .. code-block:: php add('url', new UrlValidator([ - 'message' => ':field must be a url' - ])); - - $validator->add(['url', 'homepage'], new UrlValidator([ - 'message' => [ - 'url' => 'url must be a url', - 'homepage' => 'homepage must be a url' - ] - ])); + use Phalcon\Validation\Validator\Url as UrlValidator; + + $validator->add( + "url", + new UrlValidator( + [ + "message" => ":field must be a url", + ] + ) + ); + + $validator->add( + [ + "url", + "homepage", + ], + new UrlValidator( + [ + "message" => [ + "url" => "url must be a url", + "homepage" => "homepage must be a url", + ] + ] + ) + ); @@ -60,7 +73,8 @@ Checks if an option is defined public **getOption** (*mixed* $key, [*mixed* $defaultValue]) inherited from :doc:`Phalcon\\Validation\\Validator ` -Returns an option in the validator's options Returns null if the option hasn't set +Returns an option in the validator's options +Returns null if the option hasn't set diff --git a/zh/api/Phalcon_Version.rst b/zh/api/Phalcon_Version.rst index 4322c6cb17bb..77d94d7b0e5a 100644 --- a/zh/api/Phalcon_Version.rst +++ b/zh/api/Phalcon_Version.rst @@ -27,51 +27,61 @@ 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. +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. final protected static **_getSpecial** (*mixed* $special) -Translates a number to a special release If Special release = 1 this function will return ALPHA +Translates a number to a special release +If Special release = 1 this function will return ALPHA public static **get** () -Returns the active version (string) +Returns the active version (string) .. code-block:: php