diff --git a/Library/Phalcon/Acl/Adapter/README.md b/Library/Phalcon/Acl/Adapter/README.md index 2f2559f0c..2e66f7298 100644 --- a/Library/Phalcon/Acl/Adapter/README.md +++ b/Library/Phalcon/Acl/Adapter/README.md @@ -10,17 +10,21 @@ This adapter uses a database to store the ACL list: use Phalcon\Acl\Adapter\Database as AclDb; use Phalcon\Db\Adapter\Pdo\Sqlite; -$connection = new Sqlite(['dbname' => 'sample.db']); +$connection = new Sqlite( + [ + 'dbname' => 'sample.db', + ] +); $acl = AclDb( - [ - 'db' => $connection, - 'roles' => 'roles', - 'rolesInherits' => 'roles_inherits', - 'resources' => 'resources', - 'resourcesAccesses' => 'resources_accesses', - 'accessList' => 'access_list' - ] + [ + 'db' => $connection, + 'roles' => 'roles', + 'rolesInherits' => 'roles_inherits', + 'resources' => 'resources', + 'resourcesAccesses' => 'resources_accesses', + 'accessList' => 'access_list', + ] ); ``` @@ -64,22 +68,33 @@ CREATE TABLE `roles_inherits` ( Using the cache adapter: ```php - // By default the action is deny access -$acl->setDefaultAction(Phalcon\Acl::DENY); +$acl->setDefaultAction( + \Phalcon\Acl::DENY +); // You can add roles/resources/accesses to list or insert them directly in the tables // Add roles -$acl->addRole(new Phalcon\Acl\Role('Admins')); +$acl->addRole( + new \Phalcon\Acl\Role('Admins') +); // Create the resource with its accesses -$acl->addResource('Products', ['insert', 'update', 'delete']); +$acl->addResource( + 'Products', + [ + 'insert', + 'update', + 'delete', + ] +); // Allow Admins to insert products $acl->allow('Admin', 'Products', 'insert'); // Do Admins are allowed to insert Products? -var_dump($acl->isAllowed('Admins', 'Products', 'update')); - +var_dump( + $acl->isAllowed('Admins', 'Products', 'update') +); ``` diff --git a/Library/Phalcon/Acl/Factory/README.md b/Library/Phalcon/Acl/Factory/README.md index 7575e86be..81f014dce 100644 --- a/Library/Phalcon/Acl/Factory/README.md +++ b/Library/Phalcon/Acl/Factory/README.md @@ -8,7 +8,6 @@ in case `\Phalcon\Config` or one of its adapters is used for configuration. To setup `acl` service in DI `service.php` file using `acl.ini` file: (example of structure and options in ini file can be found in [tests/_fixtures/Acl/acl.ini](tests/_fixtures/Acl/acl.ini) - ```php use Phalcon\Config\Adapter\Ini as ConfigIni; use Phalcon\Acl\Factory\Memory as AclMemory; @@ -18,10 +17,12 @@ $di->setShared( function () { $config = new ConfigIni(APP_PATH . '/config/acl.ini'); $factory = new AclMemory(); - + // returns instance of \Phalcon\Acl\Adapter\Memory // note the [acl] section in ini file - return $factory->create($config->get('acl')); + return $factory->create( + $config->get('acl') + ); } ); ``` @@ -38,7 +39,7 @@ $di->setShared( function () { $config = new Config(APP_PATH . '/config/acl.php'); $factory = new AclMemory(); - + // returns instance of \Phalcon\Acl\Adapter\Memory return $factory->create($config); } diff --git a/Library/Phalcon/Annotations/Adapter/README.md b/Library/Phalcon/Annotations/Adapter/README.md index 1f33f0a9f..917322409 100644 --- a/Library/Phalcon/Annotations/Adapter/README.md +++ b/Library/Phalcon/Annotations/Adapter/README.md @@ -10,15 +10,20 @@ This adapter uses a `Phalcon\Cache\Backend\Libmemcached` backend to store the ca ```php use Phalcon\Annotations\Adapter\Memcached; -$di->set('annotations', function () { - return new Memcached([ - 'lifetime' => 8600, - 'host' => 'localhost', - 'port' => 11211, - 'weight' => 1, - 'prefix' => 'prefix.', - ]); -}); +$di->set( + 'annotations', + function () { + return new Memcached( + [ + 'lifetime' => 8600, + 'host' => 'localhost', + 'port' => 11211, + 'weight' => 1, + 'prefix' => 'prefix.', + ] + ); + } +); ``` ## Redis @@ -29,14 +34,19 @@ This adapter uses a `Phalcon\Cache\Backend\Redis` backend to store the cached co ```php use Phalcon\Annotations\Adapter\Redis; -$di->set('annotations', function () { - return new Redis([ - 'lifetime' => 8600, - 'host' => 'localhost', - 'port' => 6379, - 'prefix' => 'annotations_', - ]); -}); +$di->set( + 'annotations', + function () { + return new Redis( + [ + 'lifetime' => 8600, + 'host' => 'localhost', + 'port' => 6379, + 'prefix' => 'annotations_', + ] + ); + } +); ``` ## Aerospike @@ -47,19 +57,27 @@ This adapter uses a `Phalcon\Cache\Backend\Aerospike` backend to store the cache ```php use Phalcon\Annotations\Adapter\Aerospike; -$di->set('annotations', function () { - return new Aerospike([ - 'hosts' => [ - ['addr' => '127.0.0.1', 'port' => 3000] - ], - 'persistent' => true, - 'namespace' => 'test', - 'prefix' => 'annotations_', - 'lifetime' => 8600, - 'options' => [ - \Aerospike::OPT_CONNECT_TIMEOUT => 1250, - \Aerospike::OPT_WRITE_TIMEOUT => 1500 - ] - ]); -}); +$di->set( + 'annotations', + function () { + return new Aerospike( + [ + 'hosts' => [ + [ + 'addr' => '127.0.0.1', + 'port' => 3000, + ], + ], + 'persistent' => true, + 'namespace' => 'test', + 'prefix' => 'annotations_', + 'lifetime' => 8600, + 'options' => [ + \Aerospike::OPT_CONNECT_TIMEOUT => 1250, + \Aerospike::OPT_WRITE_TIMEOUT => 1500, + ], + ] + ); + } +); ``` diff --git a/Library/Phalcon/Annotations/Extended/README.md b/Library/Phalcon/Annotations/Extended/README.md index ac7a64f20..62b991cc1 100644 --- a/Library/Phalcon/Annotations/Extended/README.md +++ b/Library/Phalcon/Annotations/Extended/README.md @@ -18,13 +18,18 @@ using either _APCu_ or _APC_ extension. This adapter is suitable for production. ```php use Phalcon\Annotations\Extended\Adapter\Apc; -$di->set('annotations', function () { - return new Apc([ - 'lifetime' => 8600, // Optional - 'statsSey' => '_PHAN', // Optional - 'prefix' => 'app-annotations-', // Optional - ]); -}); +$di->set( + 'annotations', + function () { + return new Apc( + [ + 'lifetime' => 8600, // Optional + 'statsSey' => '_PHAN', // Optional + 'prefix' => 'app-annotations-', // Optional + ] + ); + } +); ``` ## Memory @@ -34,9 +39,12 @@ Stores the parsed annotations in the memory. This adapter is the suitable develo ```php use Phalcon\Annotations\Extended\Adapter\Memory; -$di->set('annotations', function () { - return new Memory(); -}); +$di->set( + 'annotations', + function () { + return new Memory(); + } +); ``` ## Files diff --git a/Library/Phalcon/Avatar/README.md b/Library/Phalcon/Avatar/README.md index 46713b305..c25972781 100644 --- a/Library/Phalcon/Avatar/README.md +++ b/Library/Phalcon/Avatar/README.md @@ -14,17 +14,22 @@ Users must register their email addresses with Gravatar before their avatars wil ```php use Phalcon\Avatar\Gravatar; -$di->setShared('gravatar', function () { - // Get Gravatar instance - $gravatar = new Gravatar([]); - - // Setting default image, maximum size and maximum allowed Gravatar rating - $gravatar->setDefaultImage('retro') - ->setSize(220) - ->setRating(Gravatar::RATING_PG); - - return $gravatar; -}); +$di->setShared( + 'gravatar', + function () { + // Get Gravatar instance + $gravatar = new Gravatar( + [] + ); + + // Setting default image, maximum size and maximum allowed Gravatar rating + $gravatar->setDefaultImage('retro') + ->setSize(220) + ->setRating(Gravatar::RATING_PG); + + return $gravatar; + } +); ``` #### Setup through config @@ -40,13 +45,15 @@ $config = [ 'use_https' => true, ]; +$di->setShared( + 'gravatar', + function () use ($config) { + // Get Gravatar instance + $gravatar = new Gravatar($config); -$di->setShared('gravatar', function () use ($config) { - // Get Gravatar instance - $gravatar = new Gravatar($config); - - return $gravatar; -}); + return $gravatar; + } +); ``` ### Using @@ -156,7 +163,9 @@ By default, the Gravatar rating is `Gravatar::RATING_G`. Example: ```php -$gravatar->setRating(Gravatar::RATING_PG); +$gravatar->setRating( + Gravatar::RATING_PG +); ``` If an invalid maximum rating is specified, this method will throw an exception of class `\InvalidArgumentException`. diff --git a/Library/Phalcon/Cache/Backend/README.md b/Library/Phalcon/Cache/Backend/README.md index a48dc0c05..7c24b9eda 100644 --- a/Library/Phalcon/Cache/Backend/README.md +++ b/Library/Phalcon/Cache/Backend/README.md @@ -17,22 +17,35 @@ Usage: use Phalcon\Cache\Backend\Aerospike as BackendCache; use Phalcon\Cache\Frontend\Data; -$di->set('cache', function () { - $cache = new BackendCache(new Data(['lifetime' => 3600]), [ - 'hosts' => [ - ['addr' => '127.0.0.1', 'port' => 3000] - ], - 'persistent' => true, - 'namespace' => 'test', - 'prefix' => 'cache_', - 'options' => [ - \Aerospike::OPT_CONNECT_TIMEOUT => 1250, - \Aerospike::OPT_WRITE_TIMEOUT => 1500 - ] - ]); - - return $cache; -}); +$di->set( + 'cache', + function () { + $cache = new BackendCache( + new Data( + [ + 'lifetime' => 3600, + ] + ), + [ + 'hosts' => [ + [ + 'addr' => '127.0.0.1', + 'port' => 3000, + ], + ], + 'persistent' => true, + 'namespace' => 'test', + 'prefix' => 'cache_', + 'options' => [ + \Aerospike::OPT_CONNECT_TIMEOUT => 1250, + \Aerospike::OPT_WRITE_TIMEOUT => 1500, + ], + ] + ); + + return $cache; + } +); ``` ## Database @@ -44,26 +57,38 @@ use Phalcon\Cache\Backend\Database; use Phalcon\Cache\Frontend\Data; use Phalcon\Db\Adapter\Pdo\Mysql; -$di->set('cache', function() { - // Create a connection - $connection = new Mysql([ - 'host' => 'localhost', - 'username' => 'root', - 'password' => 'secret', - 'dbname' => 'cache_db' - ]); - - // Create a Data frontend and set a default lifetime to 1 hour - $frontend = new Data(['lifetime' => 3600]); - - // Create the cache passing the connection - $cache = new Database($frontend, [ - 'db' => $connection, - 'table' => 'cache_data' - ]); - - return $cache; -}); +$di->set( + 'cache', + function () { + // Create a connection + $connection = new Mysql( + [ + 'host' => 'localhost', + 'username' => 'root', + 'password' => 'secret', + 'dbname' => 'cache_db', + ] + ); + + // Create a Data frontend and set a default lifetime to 1 hour + $frontend = new Data( + [ + 'lifetime' => 3600, + ] + ); + + // Create the cache passing the connection + $cache = new Database( + $frontend, + [ + 'db' => $connection, + 'table' => 'cache_data', + ] + ); + + return $cache; + } +); ``` This adapter uses the following table to store the data: @@ -81,15 +106,15 @@ This adapter uses the following table to store the data: Using the cache adapter: ```php - $time = $this->cache->get('le-time'); + if ($time === null) { $time = date('r'); + $this->cache->save('le-time', $time); } echo $time; - ``` ## Wincache diff --git a/Library/Phalcon/Cli/Console/README.md b/Library/Phalcon/Cli/Console/README.md index ccb42213b..487df32ba 100644 --- a/Library/Phalcon/Cli/Console/README.md +++ b/Library/Phalcon/Cli/Console/README.md @@ -51,24 +51,26 @@ Firstly you need to add some important values into the config. ```php use Phalcon\Config; -$config = new Config([ - 'appName' => 'My Console App', - 'version' => '1.0', - - /** - * tasksDir is the absolute path to your tasks directory - * For instance, 'tasksDir' => realpath(dirname(dirname(__FILE__))).'/tasks', - */ - 'tasksDir' => '/path/to/your/project/tasks', - - /** - * annotationsAdapter is the choosen adapter to read annotations. - * Adapter by default: memory - */ - 'annotationsAdapter' => 'memory', - - 'printNewLine' => true -]); +$config = new Config( + [ + 'appName' => 'My Console App', + 'version' => '1.0', + + /** + * tasksDir is the absolute path to your tasks directory + * For instance, 'tasksDir' => realpath(dirname(dirname(__FILE__))).'/tasks', + */ + 'tasksDir' => '/path/to/your/project/tasks', + + /** + * annotationsAdapter is the chosen adapter to read annotations. + * Adapter by default: memory + */ + 'annotationsAdapter' => 'memory', + + 'printNewLine' => true, + ] +); ``` Second you must to create an instance of the DI class and add the created config class under key 'config'. @@ -77,9 +79,13 @@ Second you must to create an instance of the DI class and add the created config use Phalcon\DI\FactoryDefault\Cli as CliDi; $di = new CliDi(); -$di->set('config', function () use ($config) { - return $config; -}); + +$di->set( + 'config', + function () use ($config) { + return $config; + } +); ``` Well, it's time to create an instance of Extended Console Class to handle the calls @@ -88,7 +94,8 @@ Well, it's time to create an instance of Extended Console Class to handle the ca use Phalcon\Cli\Console\Extended as Console; $console = new Console(); -// Seting the above DI + +// Setting the above DI $console->setDI($di); /** @@ -111,6 +118,7 @@ try { $console->handle($arguments); } catch (Exception $e) { echo $e->getMessage(); + exit(255); } ``` @@ -146,7 +154,7 @@ class LsTask extends Task */ public function mainAction() { - echo 'Content list:'.PHP_EOL; + echo 'Content list:' . PHP_EOL; // Code to iterate a directory and show the content } @@ -155,18 +163,21 @@ class LsTask extends Task * @param({'type'='string', 'name'='directory', 'description'='directory to be listed' }) * @param({'type'='string', 'name'='Size unit', 'description'='Unit size to be shown' }) */ - public function hrAction(array $params) { + public function hrAction(array $params) + { $directoryToList = $params[0]; $unitSize = $params[1]; + // Code to iterate a directory and show the content } - + /** * @DoNotCover */ public function secretAction() { - echo 'Secret list:'.PHP_EOL; + echo 'Secret list:' . PHP_EOL; + // ... } } diff --git a/Library/Phalcon/Cli/Environment/README.md b/Library/Phalcon/Cli/Environment/README.md index 075e6d57d..6aaa34432 100644 --- a/Library/Phalcon/Cli/Environment/README.md +++ b/Library/Phalcon/Cli/Environment/README.md @@ -34,6 +34,9 @@ use Phalcon\DiInterface; class Console extends PhConsole implements EnvironmentAwareInterface { + /** + * @var EnvironmentInterface|null + */ protected $environment; public function __construct(DiInterface $di = null) @@ -65,7 +68,9 @@ use MyAwesomeApplication\Console; $application = new Console; -$application->setEnvironment(new Environment); +$application->setEnvironment( + new Environment +); ``` ## Implementing your own Environment diff --git a/Library/Phalcon/Db/Adapter/README.md b/Library/Phalcon/Db/Adapter/README.md index 6112b1e93..48231b460 100644 --- a/Library/Phalcon/Db/Adapter/README.md +++ b/Library/Phalcon/Db/Adapter/README.md @@ -14,23 +14,41 @@ use Phalcon\Cache\Backend\File; use Phalcon\Cache\Frontend\Data; use Phalcon\Db\Adapter\Cacheable\Mysql; -$di->set('db', function() { - /** @var \Phalcon\DiInterface $this */ - $connection = new Mysql([ - 'host' => $this->getShared('config')->database->host, - 'username' => $this->getShared('config')->database->username, - 'password' => $this->getShared('config')->database->password, - 'dbname' => $this->getShared('config')->database->name, - 'options' => [Pdo::ATTR_EMULATE_PREPARES => false] - ]); - - $frontCache = new Data(['lifetime' => 2592000]); - - // File backend settings - $connection->setCache(new File($frontCache, ['cacheDir' => __DIR__ . '/../../var/db/'])); - - return $connection; -}); +$di->set( + 'db', + function () { + /** @var \Phalcon\DiInterface $this */ + $connection = new Mysql( + [ + 'host' => $this->getShared('config')->database->host, + 'username' => $this->getShared('config')->database->username, + 'password' => $this->getShared('config')->database->password, + 'dbname' => $this->getShared('config')->database->name, + 'options' => [ + Pdo::ATTR_EMULATE_PREPARES => false, + ], + ] + ); + + $frontCache = new Data( + [ + 'lifetime' => 2592000, + ] + ); + + // File backend settings + $connection->setCache( + new File( + $frontCache, + [ + 'cacheDir' => __DIR__ . '/../../var/db/', + ] + ) + ); + + return $connection; + } +); ``` ## Pdo\Oracle @@ -40,16 +58,24 @@ Specific functions for the Oracle RDBMS. ```php use Phalcon\Db\Adapter\Pdo\Oracle; -$di->set('db', function() { - /** @var \Phalcon\DiInterface $this */ - $connection = new Oracle([ - 'dbname' => $this->getShared('config')->database->dbname, - 'username' => $this->getShared('config')->database->username, - 'password' => $this->getShared('config')->database->password, - ]); - - return $connection; -}); +$di->set( + 'db', + function () { + /** @var \Phalcon\DiInterface $this */ + + $config = $this->getShared('config'); + + $connection = new Oracle( + [ + 'dbname' => $config->database->dbname, + 'username' => $config->database->username, + 'password' => $config->database->password, + ] + ); + + return $connection; + } +); ``` ## Mongo\Client @@ -61,12 +87,17 @@ This will solve cursor and related records problems on the ODM. ```php use Phalcon\Db\Adapter\Mongo\Client; -$di->setShared('mongo', function() { - /** @var \Phalcon\DiInterface $this */ - $mongo = new Client(); +$di->setShared( + 'mongo', + function () { + /** @var \Phalcon\DiInterface $this */ + $mongo = new Client(); - return $mongo->selectDB($this->getShared('config')->database->dbname); -}); + return $mongo->selectDB( + $this->getShared('config')->database->dbname + ); + } +); ``` ## MongoDB\Client @@ -80,30 +111,39 @@ use Phalcon\Mvc\Collection\Manager; use Phalcon\Db\Adapter\MongoDB\Client; // Initialise the mongo DB connection. -$di->setShared('mongo', function () { - /** @var \Phalcon\DiInterface $this */ - $config = $this->getShared('config'); - - if (!$config->database->mongo->username || !$config->database->mongo->password) { - $dsn = 'mongodb://' . $config->database->mongo->host; - } else { - $dsn = sprintf( - 'mongodb://%s:%s@%s', - $config->database->mongo->username, - $config->database->mongo->password, - $config->database->mongo->host +$di->setShared( + 'mongo', + function () { + /** @var \Phalcon\DiInterface $this */ + + $config = $this->getShared('config'); + + if (!$config->database->mongo->username || !$config->database->mongo->password) { + $dsn = 'mongodb://' . $config->database->mongo->host; + } else { + $dsn = sprintf( + 'mongodb://%s:%s@%s', + $config->database->mongo->username, + $config->database->mongo->password, + $config->database->mongo->host + ); + } + + $mongo = new Client($dsn); + + return $mongo->selectDatabase( + $config->database->mongo->dbname ); } - - $mongo = new Client($dsn); - - return $mongo->selectDatabase($config->database->mongo->dbname); -}); +); // Collection Manager is required for MongoDB -$di->setShared('collectionManager', function () { - return new Manager(); -}); +$di->setShared( + 'collectionManager', + function () { + return new Manager(); + } +); ``` Collection example: @@ -116,7 +156,7 @@ class UserCollection extends MongoCollection public $name; public $email; public $password; - + public function getSource() { return 'users'; diff --git a/Library/Phalcon/Db/Dialect/README.md b/Library/Phalcon/Db/Dialect/README.md index 21140664f..2004aa0d2 100644 --- a/Library/Phalcon/Db/Dialect/README.md +++ b/Library/Phalcon/Db/Dialect/README.md @@ -12,15 +12,20 @@ these syntax you can use these functions: use Phalcon\Db\Adapter\Pdo\Mysql; use Phalcon\Db\Dialect\MysqlExtended; -$di->set('db', function() { - return new Mysql([ - 'host' => 'localhost', - 'username' => 'root', - 'password' => 'secret', - 'dbname' => 'enigma', - 'dialectClass' => MysqlExtended::class, - ]); -}); +$di->set( + 'db', + function () { + return new Mysql( + [ + 'host' => 'localhost', + 'username' => 'root', + 'password' => 'secret', + 'dbname' => 'enigma', + 'dialectClass' => MysqlExtended::class, + ] + ); + } +); ``` Usage: @@ -57,12 +62,17 @@ Generates database specific SQL for the Oracle RDBMS. use Phalcon\Db\Adapter\Pdo\Oracle; use Phalcon\Db\Adapter\Pdo\Oracle as Connection; -$di->set('db', function() { - return new Connection([ - 'dbname' => '//localhost/enigma', - 'username' => 'oracle', - 'password' => 'secret', - 'dialectClass' => Oracle::class, - ]); -}); +$di->set( + 'db', + function () { + return new Connection( + [ + 'dbname' => '//localhost/enigma', + 'username' => 'oracle', + 'password' => 'secret', + 'dialectClass' => Oracle::class, + ] + ); + } +); ``` diff --git a/Library/Phalcon/Error/README.md b/Library/Phalcon/Error/README.md index 0876c5127..af6840eae 100644 --- a/Library/Phalcon/Error/README.md +++ b/Library/Phalcon/Error/README.md @@ -11,12 +11,12 @@ use Phalcon\Logger\Adapter\File as FileLogger; use Phalcon\Logger\Formatter\Line as LineFormatter; return [ - 'error' => [ - 'logger' => new FileLogger(ROOT_PATH . '/log/' . APPLICATION_ENV . '.log'), - 'formatter' => new LineFormatter('[%date%][%type%] %message%', 'Y-m-d H:i:s O'), - 'controller' => 'error', - 'action' => 'index', - ] + 'error' => [ + 'logger' => new FileLogger(ROOT_PATH . '/log/' . APPLICATION_ENV . '.log'), + 'formatter' => new LineFormatter('[%date%][%type%] %message%', 'Y-m-d H:i:s O'), + 'controller' => 'error', + 'action' => 'index', + ], ]; ``` @@ -34,18 +34,19 @@ error handler has to be registered. Application must also define constants for a ```php class Application extends \Phalcon\Mvc\Application { - const ENV_PRODUCTION = 'production'; - const ENV_STAGING = 'staging'; - const ENV_TEST = 'test'; - const ENV_DEVELOPMENT = 'development'; - - public function __construct(DiInterface $dependencyInjector = null) - { - $this->_registerAutoloaders(); - ErrorHandler::register(); - - parent::__construct($dependencyInjector); - } + const ENV_PRODUCTION = 'production'; + const ENV_STAGING = 'staging'; + const ENV_TEST = 'test'; + const ENV_DEVELOPMENT = 'development'; + + public function __construct(DiInterface $dependencyInjector = null) + { + $this->_registerAutoloaders(); + + ErrorHandler::register(); + + parent::__construct($dependencyInjector); + } } ``` @@ -54,30 +55,32 @@ In the error controller `\Phalcon\Error\Error` can be retrieved through the disp ```php public function indexAction() { - /** @var \Phalcon\Error\Error $error */ - $error = $this->dispatcher->getParam('error'); - - switch ($error->type()) { - case 404: - $code = 404; - break; - case 403: - $code = 403; - break; - case 401: - $code = 401; - break; - default: - $code = 500; - } - - $this->response->resetHeaders()->setStatusCode($code, null); - - $this->view->setVars([ - 'error' => $error, - 'code' => $code, - 'dev' => APPLICATION_ENV != \Phalcon\Error\Application::ENV_PRODUCTION - ]); + /** @var \Phalcon\Error\Error $error */ + $error = $this->dispatcher->getParam('error'); + + switch ($error->type()) { + case 404: + $code = 404; + break; + case 403: + $code = 403; + break; + case 401: + $code = 401; + break; + default: + $code = 500; + } + + $this->response->resetHeaders()->setStatusCode($code, null); + + $this->view->setVars( + [ + 'error' => $error, + 'code' => $code, + 'dev' => (APPLICATION_ENV != \Phalcon\Error\Application::ENV_PRODUCTION), + ] + ); } ``` @@ -89,9 +92,9 @@ Error message could be displayed to the user this way: message(); ?> -
in file(); ?> on line line(); ?>
- isException()) { ?> -
exception()->getTraceAsString(); ?>
- +
in file(); ?> on line line(); ?>
+ isException()) { ?> +
exception()->getTraceAsString(); ?>
+ ``` diff --git a/Library/Phalcon/Http/Client/README.md b/Library/Phalcon/Http/Client/README.md index 1dadc1377..30ed337b9 100644 --- a/Library/Phalcon/Http/Client/README.md +++ b/Library/Phalcon/Http/Client/README.md @@ -19,27 +19,36 @@ $provider->setBaseUri('http://example.com/api/'); $provider->header->set('Accept', 'application/json'); // GET request to http://example.com/api/me/images?access_token=1234 and return response -$response = $provider->get('me/images', [ - 'access_token' => 1234 -]); +$response = $provider->get( + 'me/images', + [ + 'access_token' => 1234, + ] +); echo $response->body; // POST multipart/form-data request to http://example.com/api/me/images -$response = $provider->post('me/images', [ - 'access_token' => 1234, - 'image' => '@/home/mine/myimage.jpg' -]); +$response = $provider->post( + 'me/images', + [ + 'access_token' => 1234, + 'image' => '@/home/mine/myimage.jpg', + ] +); echo $response->body; echo $response->header->get('Content-Type'); echo $response->header->statusCode; // DELETE request to http://example.com/api/me/images -$response = $provider->delete('me/images', [ - 'access_token' => 1234, - 'image_id' => '321' -]); +$response = $provider->delete( + 'me/images', + [ + 'access_token' => 1234, + 'image_id' => '321', + ] +); echo $response->body; ``` diff --git a/Library/Phalcon/Http/README.md b/Library/Phalcon/Http/README.md index 6c76a0990..98d4c9a17 100644 --- a/Library/Phalcon/Http/README.md +++ b/Library/Phalcon/Http/README.md @@ -4,7 +4,7 @@ Uri utility ## Uri -The utility to parse URI strings. Resolve absolute, relative URN and querystrings. Build new URI from actual object's statement. +The utility to parse URI strings. Resolve absolute, relative URN and query strings. Build new URI from actual object's statement. ### Examples @@ -16,16 +16,17 @@ $uri1 = new Uri('http://phalconphp.com/foo/bar/baz?var1=a&var2=1'); $uri2 = $uri1->resolve('/last'); echo $uri2->build(); // http://phalconphp.com/last?var1=a&var2=1 - $uri3 = $uri1->resolve('last'); echo $uri3->build(); // http://phalconphp.com/foo/bar/baz/last?var1=a&var2=1 -$uri4 = new Uri([ - 'scheme' => 'https', - 'host' => 'admin.example.com', - 'user' => 'john', - 'pass' => 'doe' -]); +$uri4 = new Uri( + [ + 'scheme' => 'https', + 'host' => 'admin.example.com', + 'user' => 'john', + 'pass' => 'doe', + ] +); $uri5 = $uri1->resolve($uri4); echo $uri5->build(); // https://john:doe@admin.example.com/foo/bar/baz?var1=a&var2=1 diff --git a/Library/Phalcon/Logger/README.md b/Library/Phalcon/Logger/README.md index 3e751c5e9..de2a0c0c3 100644 --- a/Library/Phalcon/Logger/README.md +++ b/Library/Phalcon/Logger/README.md @@ -10,23 +10,29 @@ Adapter to store logs in a database table: use Phalcon\Db\Adapter\Pdo\Mysql; use Phalcon\Logger\Adapter\Database as DbLogger; -$di->set('logger', function() { - - $connection = new Mysql([ - 'host' => 'localhost', - 'username' => 'root', - 'password' => 'secret', - 'dbname' => 'audit' - ]); - - $logger = new DbLogger('errors', [ - 'db' => $connection, - 'table' => 'logs' - ]); - - return $logger; -}); - +$di->set( + 'logger', + function () { + $connection = new Mysql( + [ + 'host' => 'localhost', + 'username' => 'root', + 'password' => 'secret', + 'dbname' => 'audit', + ] + ); + + $logger = new DbLogger( + 'errors', + [ + 'db' => $connection, + 'table' => 'logs', + ] + ); + + return $logger; + } +); ``` The following table is used to store the logs: @@ -63,15 +69,20 @@ Adapter to send messages by UDP protocol to external server ```php use Phalcon\Logger\Adapter\Udplogger as UdpLogger; -$di->set('logger', function() { - - $logger = new UdpLogger('errors', [ - 'url' => $url, - 'port' => $port - ]); - - return $logger; -}); +$di->set( + 'logger', + function () { + $logger = new UdpLogger( + 'errors', + [ + 'url' => $url, + 'port' => $port, + ] + ); + + return $logger; + } +); ``` ## Multiple file logger @@ -101,33 +112,33 @@ Note that similar-level logs are logged into the same file. The log level groups are defined within the `getTypeString()` method. You may overload this method to fit your needs: ```php - private function getTypeString($type) - { - switch ($type) { - case Logger::EMERGENCY: - case Logger::EMERGENCE: - case Logger::CRITICAL: - // emergence, critical - return 'critical'; - case Logger::ALERT: - case Logger::ERROR: - // error, alert - return 'error'; - case Logger::WARNING: - // warning - return 'warning'; - case Logger::NOTICE: - case Logger::INFO: - // info, notice - return 'info'; - case Logger::DEBUG: - case Logger::CUSTOM: - case Logger::SPECIAL: - default: - // debug, log, custom, special - return 'debug'; - } +private function getTypeString($type) +{ + switch ($type) { + case Logger::EMERGENCY: + case Logger::EMERGENCE: + case Logger::CRITICAL: + // emergence, critical + return 'critical'; + case Logger::ALERT: + case Logger::ERROR: + // error, alert + return 'error'; + case Logger::WARNING: + // warning + return 'warning'; + case Logger::NOTICE: + case Logger::INFO: + // info, notice + return 'info'; + case Logger::DEBUG: + case Logger::CUSTOM: + case Logger::SPECIAL: + default: + // debug, log, custom, special + return 'debug'; } +} ``` Thus, by default both errors and alerts are logged into error.log, and both emergence and critical messages are logged into critical.log, etc. @@ -139,12 +150,15 @@ Optionally, you may pass configuration options to the logger constructor: ```php use Phalcon\Logger\Adapter\File\Multiple as MultipleLogger; -$logger = new MultipleLogger(__DIR__ . '/../logs', [ - // filename prefix to all logs generated by this logger. Defaults to "" - 'prefix' => 'myapp-', - // filename extension to all logs generated by this logger. Defaults to "log" - 'extension' => 'txt' -]); +$logger = new MultipleLogger( + __DIR__ . '/../logs', + [ + // filename prefix to all logs generated by this logger. Defaults to "" + 'prefix' => 'myapp-', + // filename extension to all logs generated by this logger. Defaults to "log" + 'extension' => 'txt', + ] +); ``` diff --git a/Library/Phalcon/Mailer/CHANGELOG.md b/Library/Phalcon/Mailer/CHANGELOG.md index 54d0f1ef9..e966f5f49 100644 --- a/Library/Phalcon/Mailer/CHANGELOG.md +++ b/Library/Phalcon/Mailer/CHANGELOG.md @@ -8,4 +8,4 @@ - In `\Phalcon\Mailer\Message`, creation SwiftMailer of instances moved to the DI ## v1.0.0 (2014-09-14) -- Release of component :) \ No newline at end of file +- Release of component :) diff --git a/Library/Phalcon/Mailer/README.md b/Library/Phalcon/Mailer/README.md index b2aadfbec..c06d23906 100644 --- a/Library/Phalcon/Mailer/README.md +++ b/Library/Phalcon/Mailer/README.md @@ -15,9 +15,9 @@ $config = [ 'username' => 'example@gmail.com', 'password' => 'your_password', 'from' => [ - 'email' => 'example@gmail.com', - 'name' => 'YOUR FROM NAME' - ] + 'email' => 'example@gmail.com', + 'name' => 'YOUR FROM NAME', + ], ]; ``` @@ -29,8 +29,8 @@ $config = [ 'sendmail' => '/usr/sbin/sendmail -bs', 'from' => [ 'email' => 'example@gmail.com', - 'name' => 'YOUR FROM NAME' - ] + 'name' => 'YOUR FROM NAME', + ], ]; ``` @@ -41,8 +41,8 @@ $config = [ 'driver' => 'mail', 'from' => [ 'email' => 'example@gmail.com', - 'name' => 'YOUR FROM NAME' - ] + 'name' => 'YOUR FROM NAME', + ], ]; ``` diff --git a/Library/Phalcon/Mvc/Model/Behavior/README.md b/Library/Phalcon/Mvc/Model/Behavior/README.md index f9f6268cb..4224930f6 100644 --- a/Library/Phalcon/Mvc/Model/Behavior/README.md +++ b/Library/Phalcon/Mvc/Model/Behavior/README.md @@ -12,12 +12,16 @@ class Categories extends \Phalcon\Mvc\Model { public function initialize() { - $this->addBehavior(new NestedSetBehavior([ - 'rootAttribute' => 'root', - 'leftAttribute' => 'lft', - 'rightAttribute' => 'rgt', - 'levelAttribute' => 'level' - ])); + $this->addBehavior( + new NestedSetBehavior( + [ + 'rootAttribute' => 'root', + 'leftAttribute' => 'lft', + 'rightAttribute' => 'rgt', + 'levelAttribute' => 'level', + ] + ) + ); } } ``` @@ -128,12 +132,24 @@ Result: Mercedes node and Audi node. You can get the whole tree using standard model methods like the following. For single tree per table: ```php -Categories::find(['order' => 'lft']); +Categories::find( + [ + 'order' => 'lft', + ] +); ``` For multiple trees per table: ```php -Categories::find(['root=:root:', 'order'=>'lft', 'bind' => ['root' => $root_id]]); +Categories::find( + [ + 'root=:root:', + 'order' => 'lft', + 'bind' => [ + 'root' => $root_id, + ], + ] +); ``` ### Modifying a tree @@ -278,7 +294,7 @@ $audi = Categories::findFirst(3); $ford = Categories::findFirst(4); $mercedes = Categories::findFirst(5); -foreach([$audi,$ford,$mercedes] as $category) { +foreach ([$audi,$ford,$mercedes] as $category) { $category->moveAsLast($cars); } ``` @@ -405,7 +421,7 @@ public function initialize() new Blameable( [ 'auditClass' => MyAudit::class, - 'auditDetailClass' => MyAuditDetail::class + 'auditDetailClass' => MyAuditDetail::class, ] ) ); @@ -416,6 +432,7 @@ Also by default `Audit` class will look for userName key in session for getting You can change this behavior by: ```php +use Phalcon\DiInterface; use Phalcon\Mvc\Model\Behavior\Blameable; public function initialize() @@ -423,9 +440,9 @@ public function initialize() $this->addBehavior( new Blameable( [ - 'userCallback' => function(Phalcon\DiInterface $di) { + 'userCallback' => function (DiInterface $di) { // your custom code to return user name - } + }, ] ) ); @@ -443,7 +460,7 @@ public function initialize() $this->addBehavior( new Blameable( [ - 'snapshotUpdatingDisabled' => true + 'snapshotUpdatingDisabled' => true, ] ) ); diff --git a/Library/Phalcon/Mvc/Model/MetaData/README.md b/Library/Phalcon/Mvc/Model/MetaData/README.md index 44a0f9fca..20e6fcad0 100644 --- a/Library/Phalcon/Mvc/Model/MetaData/README.md +++ b/Library/Phalcon/Mvc/Model/MetaData/README.md @@ -7,9 +7,14 @@ Usage examples of the adapters available here: This adapter uses a Wincache backend to store the cached content: ```php -$di->set('modelsMetadata', function () { - return new \Phalcon\Mvc\Model\MetaData\Wincache([ - 'lifetime' => 8600, - ]); -}); +$di->set( + 'modelsMetadata', + function () { + return new \Phalcon\Mvc\Model\MetaData\Wincache( + [ + 'lifetime' => 8600, + ] + ); + } +); ``` diff --git a/Library/Phalcon/Mvc/Model/README.md b/Library/Phalcon/Mvc/Model/README.md index 9a1be86df..c79ff793e 100644 --- a/Library/Phalcon/Mvc/Model/README.md +++ b/Library/Phalcon/Mvc/Model/README.md @@ -33,7 +33,13 @@ $robots = Loader::fromResultset(Robot::find(), 'Parts'); # Equivalent to the sec $robots = Robot::with('Parts', 'Foo.Bar'); // And arguments can be passed to the find method -$robots = Robot::with('Parts', 'Foo.Bar', ['limit' => 5]); +$robots = Robot::with( + 'Parts', + 'Foo.Bar', + [ + 'limit' => 5, + ] +); // And constraints $robots = Robot::with( @@ -42,10 +48,10 @@ $robots = Robot::with( 'Foo.Bar' => function (QueryBuilder $builder) { // Limit Bar $builder->limit(5); - } + }, ], [ - 'limit' => 5 + 'limit' => 5, ] ); diff --git a/Library/Phalcon/Mvc/View/Engine/README.md b/Library/Phalcon/Mvc/View/Engine/README.md index e30dde550..d9ad6403f 100644 --- a/Library/Phalcon/Mvc/View/Engine/README.md +++ b/Library/Phalcon/Mvc/View/Engine/README.md @@ -7,13 +7,14 @@ Mustache -------- [Mustache](https://github.com/bobthecow/mustache.php) is a logic-less template engine available for many platforms and languages. A PHP implementation is available in -[this Github repository](https://github.com/bobthecow/mustache.php). +[this GitHub repository](https://github.com/bobthecow/mustache.php). You need to manually load the Mustache library before use its engine adapter. Either registering an autoload function or including the relevant file first can achieve this. ```php require "path/to/Mustache/Autoloader.php"; + Mustache_Autoloader::register(); ``` @@ -21,18 +22,22 @@ Register the adapter in the view component: ```php //Setting up the view component -$di->set('view', function() { - - $view = new \Phalcon\Mvc\View(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - ['.mhtml' => 'Phalcon\Mvc\View\Engine\Mustache'] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new \Phalcon\Mvc\View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.mhtml' => 'Phalcon\Mvc\View\Engine\Mustache', + ] + ); + + return $view; + } +); ``` Twig @@ -43,24 +48,29 @@ You need to manually load the Twig library before use its engine adapter. Regist ```php require "path/to/Twig/Autoloader.php"; + Twig_Autoloader::register(); ``` Register the adapter in the view component: ```php // Setting up the view component -$di->set('view', function() { - - $view = new \Phalcon\Mvc\View(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - ['.twig' => 'Phalcon\Mvc\View\Engine\Twig'] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new \Phalcon\Mvc\View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.twig' => 'Phalcon\Mvc\View\Engine\Twig', + ] + ); + + return $view; + } +); ``` or @@ -70,26 +80,31 @@ use Phalcon\Mvc\View; use Phalcon\Mvc\View\Engine\Twig; // Setting up the view component -$di->set('view', function() { - - $view = new View(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - [ - '.twig' => function($view, $di) { - // Setting up Twig Environment Options - $options = ['cache' => '../cache/']; - $twig = new Twig($view, $di, $options); - - return $twig; - } - ] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.twig' => function ($view, $di) { + // Setting up Twig Environment Options + $options = [ + 'cache' => '../cache/', + ]; + + $twig = new Twig($view, $di, $options); + + return $twig; + } + ] + ); + + return $view; + } +); ``` You can also create your own defined functions to extend Twig parsing capabilities by passing a forth parameter to the Twig constructor that consists of an Array of Twig_SimpleFunction elements. This will allow you to extend Twig, or even override default functions, with your own. @@ -100,38 +115,42 @@ use Phalcon\Mvc\View; use Phalcon\Mvc\View\Engine\Twig; // Setting up the view component -$di->set('view', function() { - - $view = new View(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - [ - '.twig' => function($view, $di) { - // Setting up Twig Environment Options - $options = ['cache' => '../cache/']; - - // Adding support for the native PHP chunk_split function - $user_functions = [ - new Twig_SimpleFunction( - 'chunk_split', - function ($string, $len = 76, $end = "\r\n") use ($di) { - return chunk_split($string, $len, $end); - }, - $options - ), - ]; - - $twig = new Twig($view, $di, $options, $user_functions); - - return $twig; - } - ] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.twig' => function ($view, $di) { + // Setting up Twig Environment Options + $options = [ + 'cache' => '../cache/', + ]; + + // Adding support for the native PHP chunk_split function + $userFunctions = [ + new Twig_SimpleFunction( + 'chunk_split', + function ($string, $len = 76, $end = "\r\n") { + return chunk_split($string, $len, $end); + }, + $options + ), + ]; + + $twig = new Twig($view, $di, $options, $userFunctions); + + return $twig; + } + ] + ); + + return $view; + } +); ``` The engine implements "assets" tag in Twig templates: @@ -177,41 +196,49 @@ Register the adapter in the view component: use Phalcon\Mvc\View; // Setting up the view component -$di->set('view', function() { - - $view = new View(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - ['.tpl' => 'Phalcon\Mvc\View\Engine\Smarty'] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.tpl' => \Phalcon\Mvc\View\Engine\Smarty::class, + ] + ); + + return $view; + } +); ``` -Smarty's equivalent to Phalcon's "setVar($key, $value)" function is "assign($key, $value, $nocache = false)" which has a third optional argument. This third argument, when set to true, marks the variable as exempt from caching. This is an essential Smarty feature that other template engines lack, being useful for pages that have portions that are often changing such as the current user who is logged in. If you want to utilize this additional argument, use the incubator SmartyView instead of View which extends View to include this functionality. +Smarty's equivalent to Phalcon's `setVar($key, $value)` function is `assign($key, $value, $nocache = false)` which has a third optional argument. This third argument, when set to true, marks the variable as exempt from caching. This is an essential Smarty feature that other template engines lack, being useful for pages that have portions that are often changing such as the current user who is logged in. If you want to utilize this additional argument, use the incubator SmartyView instead of View which extends View to include this functionality. ```php use Phalcon\Mvc\View\SmartyView; // Setting up the view component -$di->set('view', function() { - - $view = new SmartyView(); - - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - ['.tpl' => 'Phalcon\Mvc\View\Engine\Smarty'] - ); - - return $view; -}); +$di->set( + 'view', + function () { + $view = new SmartyView(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.tpl' => \Phalcon\Mvc\View\Engine\Smarty::class, + ] + ); + + return $view; + } +); ``` -You may now use the setVar function you are familiar with in Phalcon with the third, optional argument: +You may now use the `setVar()` method you are familiar with in Phalcon with the third, optional argument: ```php // This variable is exempt from caching @@ -227,35 +254,39 @@ Smarty can be configured to alter its default behavior, the following example ex use Phalcon\Mvc\View; use Phalcon\Mvc\View\Engine\Smarty; -$di->set('view', function() use ($config) { - - $view = new View(); - $view->setViewsDir('../app/views/'); - - $view->registerEngines( - [ - '.html' => function($view, $di) { - - $smarty = new Smarty($view, $di); - - $smarty->setOptions([ - 'template_dir' => $view->getViewsDir(), - 'compile_dir' => '../app/viewscompiled', - 'error_reporting' => error_reporting() ^ E_NOTICE, - 'escape_html' => true, - '_file_perms' => 0666, - '_dir_perms' => 0777, - 'force_compile' => false, - 'compile_check' => true, - 'caching' => false, - 'debugging' => true, - ]); - - return $smarty; - } - ] - ); - - return $view; -}); +$di->set( + 'view', + function () use ($config) { + $view = new View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + [ + '.html' => function ($view, $di) { + $smarty = new Smarty($view, $di); + + $smarty->setOptions( + [ + 'template_dir' => $view->getViewsDir(), + 'compile_dir' => '../app/viewscompiled', + 'error_reporting' => error_reporting() ^ E_NOTICE, + 'escape_html' => true, + '_file_perms' => 0666, + '_dir_perms' => 0777, + 'force_compile' => false, + 'compile_check' => true, + 'caching' => false, + 'debugging' => true, + ] + ); + + return $smarty; + } + ] + ); + + return $view; + } +); ``` diff --git a/Library/Phalcon/Paginator/README.md b/Library/Phalcon/Paginator/README.md index 75569abe6..7b7b15ce4 100644 --- a/Library/Phalcon/Paginator/README.md +++ b/Library/Phalcon/Paginator/README.md @@ -11,20 +11,24 @@ use Phalcon\Paginator\Pager; class IndexController extends Controller { - public function indexAction() { - $currentPage = abs($this->request->getQuery('page', 'int', 1)); + $currentPage = abs( + $this->request->getQuery('page', 'int', 1) + ); + if ($currentPage == 0) { $currentPage = 1; } $pager = new Pager( - new Paginator([ - 'data' => range(1, 200), - 'limit' => 10, - 'page' => $currentPage, - ]), + new Paginator( + [ + 'data' => range(1, 200), + 'limit' => 10, + 'page' => $currentPage, + ] + ), [ // We will use Bootstrap framework styles 'layoutClass' => 'Phalcon\Paginator\Pager\Layout\Bootstrap', @@ -35,11 +39,13 @@ class IndexController extends Controller // Or something like this // 'urlMask' => sprintf( // '%s?page={%%page_number}', - // $this->url->get([ - // 'for' => 'index:posts', - // 'controller' => 'index', - // 'action' => 'index' - // ]) + // $this->url->get( + // [ + // 'for' => 'index:posts', + // 'controller' => 'index', + // 'action' => 'index', + // ] + // ) // ), ] ); diff --git a/Library/Phalcon/Queue/Beanstalk/README.md b/Library/Phalcon/Queue/Beanstalk/README.md index 082e1283d..8b31b39db 100644 --- a/Library/Phalcon/Queue/Beanstalk/README.md +++ b/Library/Phalcon/Queue/Beanstalk/README.md @@ -19,10 +19,12 @@ class IndexController extends Controller { if ($this->request->isPost()) { // Connect to the queue - $beanstalk = new BeanstalkExtended([ - 'host' => '192.168.0.21', - 'prefix' => 'project-name', - ]); + $beanstalk = new BeanstalkExtended( + [ + 'host' => '192.168.0.21', + 'prefix' => 'project-name', + ] + ); // Save the video info in database and send it to post-process $beanstalk->putInTube('processVideo', 4871); @@ -35,19 +37,20 @@ class IndexController extends Controller public function deleteVideoAction() { // Connect to the queue - $beanstalk = new BeanstalkExtended([ - 'host' => '192.168.0.21', - 'prefix' => 'project-name', - ]); + $beanstalk = new BeanstalkExtended( + [ + 'host' => '192.168.0.21', + 'prefix' => 'project-name', + ] + ); // Send the command to physical unlink to the queue $beanstalk->putInTube('deleteVideo', 4871); } - } ``` -Now handle the queues in console script (e.g.: php app/bin/video.php): +Now handle the queues in console script (e.g.: `php app/bin/video.php`): ```php #!/usr/bin/env php @@ -55,34 +58,45 @@ Now handle the queues in console script (e.g.: php app/bin/video.php): /** * Workers that handles queues related to the videos. */ + use Phalcon\Queue\Beanstalk\Extended as BeanstalkExtended; use Phalcon\Queue\Beanstalk\Job; $host = '192.168.0.21'; -$beanstalk = new BeanstalkExtended([ - 'host' => $host, - 'prefix' => 'project-name', -]); - -$beanstalk->addWorker($host.'processVideo', function (Job $job) { - // Here we should collect the meta information, - // make the screenshots, convert the video to the FLV etc. - $videoId = $job->getBody(); - - // It's very important to send the right exit code! - exit(0); -}); +$beanstalk = new BeanstalkExtended( + [ + 'host' => $host, + 'prefix' => 'project-name', + ] +); + +$beanstalk->addWorker( + $host . 'processVideo', + function (Job $job) { + // Here we should collect the meta information, + // make the screenshots, convert the video to the FLV etc. + $videoId = $job->getBody(); + + // It's very important to send the right exit code! + exit(0); + } +); -$beanstalk->addWorker($host.'deleteVideo', function (Job $job) { - // Here we should collect the meta information, - // make the screenshots, convert the video to the FLV etc. - $videoId = $job->getBody(); +$beanstalk->addWorker( + $host . 'deleteVideo', + function (Job $job) { + // Here we should collect the meta information, + // make the screenshots, convert the video to the FLV etc. + $videoId = $job->getBody(); - unlink('/var/www/data/' . $videoId . '.flv'); + unlink( + '/var/www/data/' . $videoId . '.flv' + ); - exit(0); -}); + exit(0); + } +); // Start processing queues $beanstalk->doWork(); @@ -93,26 +107,35 @@ Simple console script that outputs tubes stats: ```php #!/usr/bin/env php '192.168.0.21', - 'prefix' => $prefix, -]); - -foreach ($beanstalk->getTubes() as $tube) { - if (0 === strpos($tube, $prefix)) { - try { - $stats = $beanstalk->getTubeStats($tube); - printf( - "%s:\n\tready: %d\n\treserved: %d\n", - $tube, - $stats['current-jobs-ready'], - $stats['current-jobs-reserved'] - ); - } catch (\Exception $e) { - } +$beanstalk = new BeanstalkExtended( + [ + 'host' => '192.168.0.21', + 'prefix' => $prefix, + ] +); + +$tubes = $beanstalk->getTubes(); + +foreach ($tubes as $tube) { + if (0 !== strpos($tube, $prefix)) { + continue; + } + + try { + $stats = $beanstalk->getTubeStats($tube); + + printf( + "%s:\n\tready: %d\n\treserved: %d\n", + $tube, + $stats['current-jobs-ready'], + $stats['current-jobs-reserved'] + ); + } catch (\Exception $e) { + // ... } } ``` diff --git a/Library/Phalcon/Session/Adapter/README.md b/Library/Phalcon/Session/Adapter/README.md index 5c83d5d6e..cac887b59 100644 --- a/Library/Phalcon/Session/Adapter/README.md +++ b/Library/Phalcon/Session/Adapter/README.md @@ -16,26 +16,34 @@ Usage: ```php use Phalcon\Session\Adapter\Aerospike as SessionHandler; -$di->set('session', function () { - $session = new SessionHandler([ - 'hosts' => [ - ['addr' => '127.0.0.1', 'port' => 3000] - ], - 'persistent' => true, - 'namespace' => 'test', - 'prefix' => 'session_', - 'lifetime' => 8600, - 'uniqueId' => '3Hf90KdjQ18', - 'options' => [ - \Aerospike::OPT_CONNECT_TIMEOUT => 1250, - \Aerospike::OPT_WRITE_TIMEOUT => 1500 - ] - ]); - - $session->start(); - - return $session; -}); +$di->set( + 'session', + function () { + $session = new SessionHandler( + [ + 'hosts' => [ + [ + 'addr' => '127.0.0.1', + 'port' => 3000, + ] + ], + 'persistent' => true, + 'namespace' => 'test', + 'prefix' => 'session_', + 'lifetime' => 8600, + 'uniqueId' => '3Hf90KdjQ18', + 'options' => [ + \Aerospike::OPT_CONNECT_TIMEOUT => 1250, + \Aerospike::OPT_WRITE_TIMEOUT => 1500, + ], + ] + ); + + $session->start(); + + return $session; + } +); ``` @@ -47,24 +55,31 @@ This adapter uses a database backend to store session data: use Phalcon\Db\Adapter\Pdo\Mysql; use Phalcon\Session\Adapter\Database; -$di->set('session', function() { - // Create a connection - $connection = new Mysql([ - 'host' => 'localhost', - 'username' => 'root', - 'password' => 'secret', - 'dbname' => 'test' - ]); - - $session = new Database([ - 'db' => $connection, - 'table' => 'session_data' - ]); - - $session->start(); - - return $session; -}); +$di->set( + 'session', + function () { + // Create a connection + $connection = new Mysql( + [ + 'host' => 'localhost', + 'username' => 'root', + 'password' => 'secret', + 'dbname' => 'test', + ] + ); + + $session = new Database( + [ + 'db' => $connection, + 'table' => 'session_data', + ] + ); + + $session->start(); + + return $session; + } +); ``` @@ -87,20 +102,24 @@ This adapter uses a Mongo database backend to store session data: ```php use Phalcon\Session\Adapter\Mongo as MongoSession; -$di->set('session', function() { - // Create a connection to mongo - $mongo = new \Mongo(); - - // Passing a collection to the adapter - $session = new MongoSession([ - 'collection' => $mongo->test->session_data - ]); +$di->set( + 'session', + function () { + // Create a connection to mongo + $mongo = new \Mongo(); - $session->start(); + // Passing a collection to the adapter + $session = new MongoSession( + [ + 'collection' => $mongo->test->session_data, + ] + ); - return $session; -}); + $session->start(); + return $session; + } +); ``` ## Redis @@ -111,15 +130,20 @@ You would need a [phpredis][4] extension installed to use it: ```php use Phalcon\Session\Adapter\Redis; -$di->set('session', function() { - $session = new Redis([ - 'path' => 'tcp://127.0.0.1:6379?weight=1' - ]); +$di->set( + 'session', + function () { + $session = new Redis( + [ + 'path' => 'tcp://127.0.0.1:6379?weight=1', + ] + ); - $session->start(); + $session->start(); - return $session; -}); + return $session; + } +); ``` @@ -142,24 +166,28 @@ CREATE TABLE `php_session` ( ```php use Phalcon\Session\Adapter\HandlerSocket; -$di->set('session', function() { - $session = new HandlerSocket([ - 'cookie_path' => '/', - 'cookie_domain' => '', - 'lifetime' => 3600, - 'server' => [ - 'host' => 'localhost', - 'port' => 9999, - 'dbname' => 'session', - 'dbtable' => 'php_session' - ] - ]); - - $session->start(); - - return $session; -}); - +$di->set( + 'session', + function () { + $session = new HandlerSocket( + [ + 'cookie_path' => '/', + 'cookie_domain' => '', + 'lifetime' => 3600, + 'server' => [ + 'host' => 'localhost', + 'port' => 9999, + 'dbname' => 'session', + 'dbtable' => 'php_session', + ], + ] + ); + + $session->start(); + + return $session; + } +); ``` The extension [`handlersocket`][5] is required to use this adapter. diff --git a/Library/Phalcon/Traits/README.md b/Library/Phalcon/Traits/README.md index 6f1722389..8c9813645 100644 --- a/Library/Phalcon/Traits/README.md +++ b/Library/Phalcon/Traits/README.md @@ -20,7 +20,7 @@ class MyAdapter protected $configurable = [ 'host', - 'viewsDir' + 'viewsDir', ]; public function __construct(array $options) diff --git a/Library/Phalcon/Translate/Adapter/README.md b/Library/Phalcon/Translate/Adapter/README.md index 53fd55555..c70bccd4a 100644 --- a/Library/Phalcon/Translate/Adapter/README.md +++ b/Library/Phalcon/Translate/Adapter/README.md @@ -11,14 +11,19 @@ First of all, you need to up your database. To do this, use [DI][1] (in `/public ```php use Phalcon\Db\Adapter\Pdo\Mysql; -$di->set('db', function() { - return new Mysql([ - 'host' => 'localhost', - 'username' => 'root', - 'password' => 123456, - 'dbname' => 'application' - ]); -}); +$di->set( + 'db', + function () { + return new Mysql( + [ + 'host' => 'localhost', + 'username' => 'root', + 'password' => 123456, + 'dbname' => 'application', + ] + ); + } +); ``` Then, you should get the translation through your `controller`. Put this on it: @@ -28,16 +33,18 @@ use Phalcon\Translate\Adapter\Database; class IndexController extends \Phalcon\Mvc\Controller { - protected function _getTranslation() - { - return new Database([ - 'db' => $this->di->get('db'), // Here we're getting the database from DI - 'table' => 'translations', // The table that is storing the translations - 'language' => $this->request->getBestLanguage(), // Now we're getting the best language for the user - ]); - } - - // ... + protected function _getTranslation() + { + return new Database( + [ + 'db' => $this->di->get('db'), // Here we're getting the database from DI + 'table' => 'translations', // The table that is storing the translations + 'language' => $this->request->getBestLanguage(), // Now we're getting the best language for the user + ] + ); + } + + // ... } ``` @@ -67,15 +74,18 @@ from your database. *This step happens in your controller.* Follow the example: ```php class IndexController extends \Phalcon\Mvc\Controller { - protected function _getTranslation() - { - // ... - } - - public function indexAction() - { - $this->view->setVar('expression', $this->_getTranslation()); - } + protected function _getTranslation() + { + // ... + } + + public function indexAction() + { + $this->view->setVar( + 'expression', + $this->_getTranslation() + ); + } } ``` @@ -83,12 +93,12 @@ Then, just output the`phrase/sentence/word` in your view: ```php - - - - -

_("IndexPage_Hello_World"); ?>

- + + + + +

_("IndexPage_Hello_World"); ?>

+ ``` @@ -108,10 +118,12 @@ use MessageFormatter; use Phalcon\Translate\Adapter\Mongo; use My\Application\Collections\Translate; -$translate = new Mongo([ - 'collection' => Translate::class, - 'language' => 'en' -]); +$translate = new Mongo( + [ + 'collection' => Translate::class, + 'language' => 'en', + ] +); echo $translate->t('application.title'); ``` @@ -126,14 +138,22 @@ The extension [intl][3] must be installed in PHP. ```php use Phalcon\Translate\Adapter\ResourceBundle; -$translate = new ResourceBundle([ - 'bundle' => '/path/to/bundle', // required - 'locale' => 'en', // required - 'fallback' => false // optional, default - true -]); +$translate = new ResourceBundle( + [ + 'bundle' => '/path/to/bundle', // required + 'locale' => 'en', // required + 'fallback' => false, // optional, default - true + ] +); echo $translate->t('application.title'); -echo $translate->t('application.copyright', ['currentYear' => new \DateTime('now')]); + +echo $translate->t( + 'application.copyright', + [ + 'currentYear' => new \DateTime('now'), + ] +); ``` ResourceBundle source file example @@ -165,9 +185,13 @@ label_home; home; maison; casa * PHP example : ```php // the constructor is inherited from Phalcon\Translate\Adapter\Csv -$titles_translater = new Phalcon\Translate\Adapter\MultiCsv([ - 'content' => "{$config->langDir}/titles.csv" -]); +$titles_translater = new Phalcon\Translate\Adapter\MultiCsv( + [ + 'content' => "{$config->langDir}/titles.csv", + ] +); + $titles_translater->setLocale('es_ES'); + echo $titles_translater->query('label_home'); // string 'casa' ``` diff --git a/Library/Phalcon/Translate/Interpolator/README.md b/Library/Phalcon/Translate/Interpolator/README.md index 9cded505a..d6dda6118 100644 --- a/Library/Phalcon/Translate/Interpolator/README.md +++ b/Library/Phalcon/Translate/Interpolator/README.md @@ -9,28 +9,51 @@ More about the syntax convention can be read on this [formating guide](https://w ```php new Intl('en_US'), // this interpolator must be locale aware - 'content' => ['hi-name' => 'Hello {name}, it\'s {time, number, integer} o\'clock'] -]); +$translate = new NativeArray( + [ + 'interpolator' => new Intl('en_US'), // this interpolator must be locale aware + 'content' => [ + 'hi-name' => 'Hello {name}, it\'s {time, number, integer} o\'clock', + ], + ] +); $name = 'Henry'; -$translate->_('hi-name', ['name' => $name, 'time' => 8]); // Hello Henry, it's 8 o'clock + +// Hello Henry, it's 8 o'clock +$translate->_( + 'hi-name', + [ + 'name' => $name, + 'time' => 8, + ] +); ``` ```php new Intl('fr_FR'), // this interpolator must be locale aware - 'content' => ['apples' => "{count, plural, =0{Je n'ai aucune pomme} =1{J'ai une pomme} other{J'ai # pommes}}."] -]); +$translate = new NativeArray( + [ + 'interpolator' => new Intl('fr_FR'), // this interpolator must be locale aware + 'content' => [ + 'apples' => "{count, plural, =0{Je n'ai aucune pomme} =1{J'ai une pomme} other{J'ai # pommes}}.", + ], + ] +); // thousands separator is " " (blank space) for fr_FR -echo $translate->_('apples', ['count' => 1000]); // J'ai 1 000 pommes -``` \ No newline at end of file +echo $translate->_( + 'apples', + [ + 'count' => 1000, + ] +); // J'ai 1 000 pommes +``` diff --git a/Library/Phalcon/Validation/Validator/Db/README.md b/Library/Phalcon/Validation/Validator/Db/README.md index 568945f67..1b64a9072 100644 --- a/Library/Phalcon/Validation/Validator/Db/README.md +++ b/Library/Phalcon/Validation/Validator/Db/README.md @@ -1,11 +1,15 @@ # Phalcon\Validation\Validator\Db -Usage examples of db validators available here: +Usage examples of DB validators available here: ## Uniqueness ```php -$connection = new \Phalcon\Db\Adapter\Pdo\Sqlite(['dbname' => 'sample.db']); +$connection = new \Phalcon\Db\Adapter\Pdo\Sqlite( + [ + 'dbname' => 'sample.db', + ] +); $uniqueness = new \Phalcon\Validation\Validator\Db\Uniqueness( [ @@ -13,6 +17,6 @@ $uniqueness = new \Phalcon\Validation\Validator\Db\Uniqueness( 'column' => 'login', 'message' => 'already taken', ], - $connection; + $connection ); ``` diff --git a/Library/Phalcon/Validation/Validator/README.md b/Library/Phalcon/Validation/Validator/README.md index 36461d3d9..251e919f6 100644 --- a/Library/Phalcon/Validation/Validator/README.md +++ b/Library/Phalcon/Validation/Validator/README.md @@ -26,12 +26,16 @@ use Phalcon\Validation\Validator\ReCaptcha; $reCaptcha = new Hidden('g-recaptcha-response'); -$reCaptcha->setLabel('reCAPTCHA')->addValidators([ - new ReCaptcha([ - 'message' => 'The captcha is not valid', - 'secret' => 'your_site_key', - ]), -]); +$reCaptcha->setLabel('reCAPTCHA')->addValidators( + [ + new ReCaptcha( + [ + 'message' => 'The captcha is not valid', + 'secret' => 'your_site_key', + ] + ), + ] +); $this->add($reCaptcha); ``` @@ -50,13 +54,13 @@ The IpValidator validates a valid ip address. ```php $data['ip'] = $this->request->getPost('ip'); -$validation = new Phalcon\Validation(); +$validation = new \Phalcon\Validation(); $validation->add( 'ip', - new MicheleAngioni\PhalconValidators\IpValidator ( + new \MicheleAngioni\PhalconValidators\IpValidator( [ - 'message' => 'The IP is not valid.' // Optional + 'message' => 'The IP is not valid.', // Optional ] ) ); @@ -65,7 +69,6 @@ $messages = $validation->validate($data); if (count($messages)) { // Some error occurred, handle messages - } ``` @@ -83,20 +86,20 @@ Optionally also signed numbers are supported. ```php $data['number'] = $this->request->getPost('number'); -$validation = new Phalcon\Validation(); +$validation = new \Phalcon\Validation(); $validation->add( 'number', - new MicheleAngioni\PhalconValidators\NumericValidator ( + new \MicheleAngioni\PhalconValidators\NumericValidator( [ - 'allowFloat' => true, // Optional, default: false - 'allowSign' => true, // Optional, default: false - 'min' => 2, // Optional - 'min' => 2, // Optional - 'max' => 50, // Optional - 'message' => 'Only numeric (0-9,.) characters are allowed.', // Optional - 'messageMinimum' => 'The value must be at least 2', // Optional - 'messageMaximum' => 'The value must be lower than 50' // Optional + 'allowFloat' => true, // Optional, default: false + 'allowSign' => true, // Optional, default: false + 'min' => 2, // Optional + 'min' => 2, // Optional + 'max' => 50, // Optional + 'message' => 'Only numeric (0-9,.) characters are allowed.', // Optional + 'messageMinimum' => 'The value must be at least 2', // Optional + 'messageMaximum' => 'The value must be lower than 50', // Optional ] ) ); @@ -105,7 +108,6 @@ $messages = $validation->validate($data); if (count($messages)) { // Some error occurred, handle messages - } // Validation succeeded without errors @@ -119,19 +121,19 @@ Minimum and maximum string lengths can be specified. ```php $data['text'] = $this->request->getPost('text'); -$validation = new Phalcon\Validation(); +$validation = new \Phalcon\Validation(); $validation->add( 'text', - new MicheleAngioni\PhalconValidators\AlphaNumericValidator ( + new \MicheleAngioni\PhalconValidators\AlphaNumericValidator( [ - 'whiteSpace' => true, // Optional, default false - 'underscore' => true, // Optional, default false - 'min' => 6, // Optional - 'max' => 30, // Optional - 'message' => 'Validation failed.', // Optional - 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 30 characters.' // Optional + 'whiteSpace' => true, // Optional, default false + 'underscore' => true, // Optional, default false + 'min' => 6, // Optional + 'max' => 30, // Optional + 'message' => 'Validation failed.', // Optional + 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional + 'messageMaximum' => 'The value can contain maximum 30 characters.', // Optional ] ) ); @@ -140,7 +142,6 @@ $messages = $validation->validate($data); if (count($messages)) { // Some error occurred, handle messages - } // Validation succeeded without errors @@ -155,18 +156,18 @@ Minimum and maximum string lengths can be specified. ```php $data['text'] = $this->request->getPost('text'); -$validation = new Phalcon\Validation(); +$validation = new \Phalcon\Validation(); $validation->add( 'text', - new MicheleAngioni\PhalconValidators\AlphaNamesValidator ( + new \MicheleAngioni\PhalconValidators\AlphaNamesValidator( [ - 'numbers' => true, // Optional, default false - 'min' => 6, // Optional - 'max' => 30, // Optional - 'message' => 'Validation failed.', // Optional - 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 30 characters.' // Optional + 'numbers' => true, // Optional, default false + 'min' => 6, // Optional + 'max' => 30, // Optional + 'message' => 'Validation failed.', // Optional + 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional + 'messageMaximum' => 'The value can contain maximum 30 characters.', // Optional ] ) ); @@ -175,7 +176,6 @@ $messages = $validation->validate($data); if (count($messages)) { // Some error occurred, handle messages - } // Validation succeeded without errors @@ -190,20 +190,20 @@ Minimum and maximum string lengths can be specified. ```php $data['text'] = $this->request->getPost('text'); -$validation = new Phalcon\Validation(); +$validation = new \Phalcon\Validation(); $validation->add( 'text', - new MicheleAngioni\PhalconValidators\AlphaCompleteValidator ( + new \MicheleAngioni\PhalconValidators\AlphaCompleteValidator( [ - 'allowBackslashes' => true, // Optional - 'allowPipes' => true, // Optional - 'allowUrlChars' => true, // Optional - 'min' => 6, // Optional - 'max' => 30, // Optional - 'message' => 'Validation failed.', // Optional - 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional - 'messageMaximum' => 'The value can contain maximum 30 characters.' // Optional + 'allowBackslashes' => true, // Optional + 'allowPipes' => true, // Optional + 'allowUrlChars' => true, // Optional + 'min' => 6, // Optional + 'max' => 30, // Optional + 'message' => 'Validation failed.', // Optional + 'messageMinimum' => 'The value must contain at least 6 characters.', // Optional + 'messageMaximum' => 'The value can contain maximum 30 characters.', // Optional ] ) ); @@ -212,7 +212,6 @@ $messages = $validation->validate($data); if (count($messages)) { // Some error occurred, handle messages - } // Validation succeeded without errors diff --git a/README.md b/README.md index d3b3a516a..360ea6aca 100644 --- a/README.md +++ b/README.md @@ -71,9 +71,11 @@ to load classes from the incubator repository: $loader = new Phalcon\Loader(); -$loader->registerNamespaces([ - 'Phalcon' => '/path/to/incubator/Library/Phalcon/' -]); +$loader->registerNamespaces( + [ + 'Phalcon' => '/path/to/incubator/Library/Phalcon/', + ] +); $loader->register(); ```