public function resetAction() { $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($this->config->database->toArray()); $tables = $connection->listTables(); foreach ($tables as $table) { $tablename = \Phalcon\Text::camelize($table); $fd = fopen("{$this->config->application->formsDir}/{$tablename}Form.php", "w"); fwrite($fd, "<?php" . self::NL . self::NL); // Begin class fwrite($fd, "class {$tablename}Form {" . self::NL); $columns = $connection->describeColumns($table); foreach ($columns as $column) { if ($column instanceof \Phalcon\Db\Column) { // Escape if column is primary if ($column->isPrimary()) { continue; } // Begin method $columnname = \Phalcon\Text::camelize($column->getName()); fwrite($fd, self::TAB . "private function _{$columnname}() {" . self::NL); // Write element $columntype_base = $this->_getBaseType($column->getType()); $columntype = $this->_getType($columntype_base, $column); fwrite($fd, self::TAB . self::TAB . "\$element = new \\Phalcon\\Forms\\Element\\{$columntype}(\"{$columnname}\");" . self::NL); fwrite($fd, self::TAB . self::TAB . "\$element->setLabel(\"{$columnname}\");" . self::NL); // Add empty selection for select fields if ($columntype == "Select") { fwrite($fd, self::TAB . self::TAB . "\$element->setOptions([]);" . self::NL); } // Add validator on text fields if ($columntype == "Text" && $column->getSize() > 0) { fwrite($fd, self::TAB . self::TAB . "\$element->addValidator(new \\Phalcon\\Validation\\Validator\\StringLength([" . self::NL); fwrite($fd, self::TAB . self::TAB . self::TAB . "\"max\" => {$column->getSize()}" . self::NL); fwrite($fd, self::TAB . self::TAB . "]));" . self::NL); } // End method fwrite($fd, self::TAB . self::TAB . "return \$element;" . self::NL); fwrite($fd, self::TAB . "}" . self::NL); } } // Final method : construction of the form fwrite($fd, self::TAB . "public function setFields() {" . self::NL); foreach ($columns as $column) { if ($column instanceof \Phalcon\Db\Column) { if ($column->isPrimary()) { continue; } $columnname = \Phalcon\Text::camelize($column->getName()); fwrite($fd, self::TAB . self::TAB . "\$this->add(\$this->_{$columnname}());" . self::NL); } } fwrite($fd, self::TAB . "}" . self::NL); // End class fwrite($fd, "}" . self::NL . self::NL); fclose($fd); } $this->view->disable(); echo "done!"; return FALSE; }
public function testModelsMysql() { require 'unit-tests/config.db.php'; if (empty($configMysql)) { $this->markTestSkipped('Test skipped'); return; } $di = $this->_getDI(); $tracer = array(); $di->set('db', function () use(&$tracer) { require 'unit-tests/config.db.php'; $eventsManager = new Phalcon\Events\Manager(); $connection = new Phalcon\Db\Adapter\Pdo\Mysql($configMysql); $eventsManager->attach('db', function ($event, $connection) use(&$tracer) { if ($event->getType() == 'beforeQuery') { $tracer[] = $connection->getSqlStatement(); } }); $connection->setEventsManager($eventsManager); return $connection; }, true); $this->_executeTestsNormal($di, $tracer); $tracer = array(); $this->_executeTestsRenamed($di, $tracer); }
/** * Register the services here to make them general or register in the ModuleDefinition to make them module-specific */ protected function _registerServices() { $config = (include __DIR__ . "/../apps/config/config.php"); $di = new \Phalcon\DI\FactoryDefault(); $loader = new \Phalcon\Loader(); /** * We're a registering a set of directories taken from the configuration file */ $loader->registerDirs(array($config->application->libraryDir, $config->application->pluginDir))->register(); //Registering a router $di->set('router', function () { $router = new \Phalcon\Mvc\Router(); $router->setDefaultModule("frontend"); $router->add('/:controller/:action', array('module' => 'frontend', 'controller' => 1, 'action' => 2)); $router->add("/cats/index", array('module' => 'frontend', 'controller' => 'categories', 'action' => 'index')); $router->add("/cat/:params", array('module' => 'frontend', 'controller' => 'categories', 'action' => 'cat', 'params' => 1)); $router->add("/ask/:params", array('module' => 'frontend', 'controller' => 'ask', 'action' => 'ask', 'params' => 1)); $router->add("/admin/:controller/:action/:params", array('module' => 'backend', 'controller' => 1, 'action' => 2, 'params' => 3)); return $router; }); $di->set('db', function () use($config) { $mysql = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name)); $mysql->query("set names 'utf8'"); return $mysql; }); $di->set('volt', function ($view, $di) use($config) { $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array('compiledPath' => $config->volt->path, 'compiledExtension' => $config->volt->extension, 'compiledSeparator' => $config->volt->separator, 'stat' => (bool) $config->volt->stat)); return $volt; }); //Set the views cache service $di->set('viewCache', function () { //Cache data for one day by default $frontCache = new Phalcon\Cache\Frontend\Output(array("lifetime" => 86400)); //Memcached connection settings $cache = new Phalcon\Cache\Backend\File($frontCache, array("cacheDir" => "../apps/caches/")); return $cache; }); /** * If the configuration specify the use of metadata adapter use it or use memory otherwise */ $di->set('modelsMetadata', function () use($config) { if (isset($config->models->metadata)) { $metaDataConfig = $config->models->metadata; $metadataAdapter = 'Phalcon\\Mvc\\Model\\Metadata\\' . $metaDataConfig->adapter; return new $metadataAdapter(); } else { return new Phalcon\Mvc\Model\Metadata\Memory(); } }); //Start the session the first time some component request the session service $di->set('session', function () { $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); $this->setDI($di); }
public function searchAction() { $connection = new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => "localhost", "username" => "root", "password" => "", "dbname" => "test_phalcon")); $value = $this->request->getPost("value"); $resultset = $connection->query("SELECT * FROM country WHERE name LIKE '%{$value}%'"); $countries = $connection->fetchAll("SELECT * FROM country WHERE name LIKE '%{$value}%' LIMIT 5", Phalcon\Db::FETCH_ASSOC); foreach ($countries as $country) { echo $country['name'] . "!!!"; } }
public function initPersistentDB($di) { // Setup the database service $di->set('db', function () { $eventsManager = new EventsManager(); $logger = new FileLogger(__DIR__ . '/' . date('Y-m-d') . '.sql.log'); $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->info($connection->getSQLStatement()); } }); $db = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => "127.0.0.1", "username" => "root", "password" => "123456", "dbname" => "rookie", "charset" => "utf8", "persistent" => true)); $db->setEventsManager($eventsManager); return $db; }); }
public static function initDb() { $config = \Phalcon\DI::getDefault()->get('config'); $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config->database->toArray()); if (getenv('APPLICATION_ENV') == 'devel') { $eventsManager = new \Phalcon\Events\Manager(); $eventsManager->attach('db', function ($event, $connection) { if ($event->getType() == 'beforeQuery') { //Start a profile with the active connection error_log($connection->getSQLStatement() . "\n" . json_encode($connection->getSQLVariables())); } }); $connection->setEventsManager($eventsManager); } return $connection; }
<?php use App\Constants\Services as AppServices; $di = new \PhalconRest\DI\FactoryDefault(); /** * @description Phalcon - \Phalcon\Config */ $di->setShared(AppServices::CONFIG, function () use($config) { return $config; }); /** * @description Phalcon - \Phalcon\Db\Adapter\Pdo\Mysql */ $di->set(AppServices::DB, function () use($config, $di) { $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name)); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($di->get(AppServices::EVENTS_MANAGER)); return $connection; }); /** * @description Phalcon - \Phalcon\Mvc\Url */ $di->set(AppServices::URL, function () use($config) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($config->application->baseUri); return $url; }); /** * @description Phalcon - \Phalcon\Mvc\View\Simple */ $di->set(AppServices::VIEW, function () use($config) {
<?php try { $connection = new Phalcon\Db\Adapter\Pdo\Mysql(array('host' => '192.168.0.11', 'username' => 'sigma', 'password' => 'secret', 'dbname' => 'blog', 'port' => '3306')); $result = $connection->query("SELECT * FROM robots LIMIT 5"); $result->setFetchMode(Phalcon\Db::FETCH_NUM); while ($robot = $result->fetch()) { print_r($robot); } } catch (Phalcon\Db\Exception $e) { echo $e->getMessage(), PHP_EOL; }
<?php //Make a connection $connection = new Phalcon\Db\Adapter\Pdo\Mysql(array('host' => '192.168.0.11', 'username' => 'sigma', 'password' => 'secret', 'dbname' => 'blog')); //Reconnect $connection->connect();
private function getConnection() { $conn = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => "localhost", "username" => "root", "password" => "123456", "dbname" => "tutorial")); $conn->connect(); return $conn; }
$router->add('/:controller/:action/:params', array('module' => 'Admin', 'controller' => 1, 'action' => 2, 'params' => 3))->setName("common"); return $router; }; $di["url"] = function () use($di) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($di->get("config")->get("common")["baseuri"]); return $url; }; $di["session"] = function () { $session = new \Phalcon\Session\Adapter\Files(); $session->start(); return $session; }; $di["db"] = function () use($di) { $config = $di->get("config")->get("common")["db"]; $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config["host"], "username" => $config["username"], "password" => $config["password"], "dbname" => $config["dbname"], "charset" => $config["charset"])); $eventsManager = new \Phalcon\Events\Manager(); $dblog = $di->get("config")->get("common")["dblog"]; $logger = new \Phalcon\Logger\Adapter\File(__DIR__ . $dblog); $eventsManager->attach('db:beforeQuery', function ($event, $connection) use($logger) { $sqlVariables = $connection->getSQLVariables(); if (count($sqlVariables)) { $logger->log($connection->getSQLStatement() . ' ' . join(', ', $sqlVariables), \Phalcon\Logger::INFO); } else { $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); } }); $connection->setEventsManager($eventsManager); return $connection; }; $di["dbBackupTool"] = function () use($di) {
/** * Database Object, conexion primaria a la base de datos * @return DI object */ private function setDb() { $config = $this->config; $di = $this->di; $di->setShared('db', function () use($config) { // Events Manager para la base de datos $eventsManager = new \Phalcon\Events\Manager(); $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config->database->toArray()); $connection->setEventsManager($eventsManager); return $connection; }); }
public function testDbMysql() { require 'unit-tests/config.db.php'; if (empty($configMysql)) { $this->markTestSkipped("Skipped"); return; } $connection = new Phalcon\Db\Adapter\Pdo\Mysql($configMysql); //Table exist $this->assertEquals($connection->tableExists('personas'), 1); $this->assertEquals($connection->tableExists('noexist'), 0); $this->assertEquals($connection->tableExists('personas', 'phalcon_test'), 1); $this->assertEquals($connection->tableExists('personas', 'test'), 0); $expectedDescribe = $this->getExpectedColumnsMysql(); $describe = $connection->describeColumns('personas'); $this->assertEquals($describe, $expectedDescribe); $describe = $connection->describeColumns('personas', 'phalcon_test'); $this->assertEquals($describe, $expectedDescribe); //Table Options $expectedOptions = array('table_type' => 'BASE TABLE', 'auto_increment' => NULL, 'engine' => 'InnoDB', 'table_collation' => 'utf8_unicode_ci'); $options = $connection->tableOptions('personas', 'phalcon_test'); $this->assertEquals($options, $expectedOptions); //Indexes $expectedIndexes = array('PRIMARY' => Phalcon\Db\Index::__set_state(array('_name' => 'PRIMARY', '_columns' => array('id'), '_type' => 'PRIMARY')), 'robots_id' => Phalcon\Db\Index::__set_state(array('_name' => 'robots_id', '_columns' => array('robots_id'))), 'parts_id' => Phalcon\Db\Index::__set_state(array('_name' => 'parts_id', '_columns' => array('parts_id')))); $describeIndexes = $connection->describeIndexes('robots_parts'); $this->assertEquals($describeIndexes, $expectedIndexes); $describeIndexes = $connection->describeIndexes('robots_parts', 'phalcon_test'); $this->assertEquals($describeIndexes, $expectedIndexes); //Indexes $expectedIndexes = array('PRIMARY' => Phalcon\Db\Index::__set_state(array('_name' => 'PRIMARY', '_columns' => array('id'), '_type' => 'PRIMARY')), 'issue_11036_token_UNIQUE' => Phalcon\Db\Index::__set_state(array('_name' => 'issue_11036_token_UNIQUE', '_columns' => array('token'), '_type' => 'UNIQUE'))); $describeIndexes = $connection->describeIndexes('issue_11036'); $this->assertEquals($describeIndexes, $expectedIndexes); $describeIndexes = $connection->describeIndexes('issue_11036', 'phalcon_test'); $this->assertEquals($describeIndexes, $expectedIndexes); //References $expectedReferences = array('robots_parts_ibfk_1' => Phalcon\Db\Reference::__set_state(array('_referenceName' => 'robots_parts_ibfk_1', '_referencedTable' => 'robots', '_columns' => array('robots_id'), '_referencedColumns' => array('id'), '_referencedSchema' => 'phalcon_test', '_onUpdate' => 'RESTRICT', '_onDelete' => 'RESTRICT')), 'robots_parts_ibfk_2' => Phalcon\Db\Reference::__set_state(array('_referenceName' => 'robots_parts_ibfk_2', '_referencedTable' => 'parts', '_columns' => array('parts_id'), '_referencedColumns' => array('id'), '_referencedSchema' => 'phalcon_test', '_onUpdate' => 'RESTRICT', '_onDelete' => 'RESTRICT'))); $describeReferences = $connection->describeReferences('robots_parts'); $this->assertEquals($describeReferences, $expectedReferences); $describeReferences = $connection->describeReferences('robots_parts', 'phalcon_test'); $this->assertEquals($describeReferences, $expectedReferences); }
public function writeMysql($data_connector_id, $data, $queryType = "override", $primary_key = "auto") { $data_connector = DataConnector::findFirstByid($data_connector_id); $database = OrgDatabase::findFirstByorganisation_id($data_connector->organisation_id); $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array('host' => $database->db_host, 'username' => $database->db_username, 'password' => $database->db_password, 'dbname' => $database->db_name)); if ($queryType == "override") { $sql = "DROP TABLE IF EXISTS " . preg_replace("/[^A-Za-z0-9 ]/", "_", $data_connector->type) . "_" . $data_connector_id; } $sql = "CREATE TABLE IF NOT EXISTS " . preg_replace("/[^A-Za-z0-9 ]/", "_", $data_connector->type) . "_" . $data_connector_id . "("; foreach ($data['headings'] as $key => $column_name) { $type = gettype($data['0'][$key]); if ('string' == gettype($data['0'][$key])) { if (is_numeric($data['0'][$key])) { if ((int) $data['0'][$key] == (double) $data['0'][$key]) { $type = "integer"; } else { $type = "double"; } } else { if (strtotime($data['0'][$key]) != false) { $type = "date"; } else { } } } if ($type == "integer") { $sql = $sql . "`" . $column_name . "` int DEFAULT NULL, "; } elseif ($type == "double") { $sql = $sql . "`" . $column_name . "` real DEFAULT NULL, "; } elseif ($type == "date") { $sql = $sql . "`" . $column_name . "` datetime DEFAULT NULL, "; } else { $sql = $sql . "`" . $column_name . "` varchar(255) DEFAULT NULL, "; } } if ($primary_key == "auto") { $sql = $sql . "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY"; } elseif ($primary_key == "first") { $sql = $sql . "PRIMARY KEY (`" . reset($data['headings']) . "`)"; } else { $sql = $sql . "PRIMARY KEY (" . $primary_key . ")"; } $sql = $sql . ");"; $connection->query($sql); $rows = array(); $sql = "INSERT INTO " . preg_replace("/[^A-Za-z0-9 ]/", "_", $data_connector->type) . "_" . $data_connector_id . " (`" . implode("`,`", $data['headings']) . "`) VALUES "; foreach ($data as $row) { if (count($data['headings']) == count($row)) { $rows[] = "('" . implode("','", $row) . "')"; } } array_shift($rows); $sql = $sql . implode(", ", $rows) . " ON DUPLICATE KEY UPDATE "; $duplicate_values = array(); foreach ($data['headings'] as $column_name) { $duplicate_values[] = "`" . $column_name . "` =VALUES(`" . $column_name . "`)"; } $sql = $sql . implode(" ,", $duplicate_values) . ";"; $connection->query($sql); }
/** * Mount the module specific routes before the module is loaded. * Add ModuleRoutes Group and annotated controllers for parsing their routing information. * * @param \Phalcon\DiInterface $di */ public static function initRoutes(DiInterface $di) { $loader = new Loader(); $loader->registerNamespaces(['App\\Modules\\Admin' => __DIR__, 'App\\Modules\\Admin\\Models' => __DIR__ . '/Models/', 'App\\Modules\\Admin\\Controllers' => __DIR__ . '/Controllers/', 'App\\Modules\\Admin\\Controllers\\API' => __DIR__ . '/Controllers/api/'], TRUE)->register(); /** * Read application wide and module only configurations */ $appConfig = $di->get('config'); $moduleConfig = (include __DIR__ . '/config/config.php'); $di->set('moduleConfig', $moduleConfig); /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function () use($appConfig) { $url = new UrlResolver(); $url->setBaseUri($appConfig->application->baseUri); return $url; }); $di->setShared('request', function () use($appConfig) { return new \Phalcon\Http\Request(); }); /** * Read configuration */ include __DIR__ . "/../../config/env/" . $appConfig->application->environment . ".php"; $database = $di->getConfig()->application->site . $di->get('request')->getQuery("countryCode"); /** * Module specific database connection */ $di->set('dbMysql', function () use($config, $database) { $eventsManager = new \Phalcon\Events\Manager(); $logger = new FileLogger(__DIR__ . "/../../Common/logs/admin/debug.log"); //Listen all the database events $eventsManager->attach('dbMysql', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); } }); $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(['host' => $config->{$database}->host, 'username' => $config->{$database}->username, 'password' => $config->{$database}->password, 'dbname' => $config->{$database}->dbname, 'options' => array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'")]); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); return $connection; }); /** * Module specific dispatcher */ $di->setShared('dispatcher', function () use($di) { $dispatcher = new Dispatcher(); $dispatcher->setDefaultNamespace('App\\Modules\\Admin\\Controllers\\'); return $dispatcher; }); $di->set('utils', function () { require __DIR__ . "/../../Common/Lib/Application/Plugins/Utils.php"; $utils = new Utils(); return $utils; }); /** * If our request contains a body, it has to be valid JSON. This parses the * body into a standard Object and makes that available from the DI. If this service * is called from a function, and the request body is not valid JSON or is empty, * the program will throw an Exception. */ $di->setShared('requestBody', function () { parse_str(file_get_contents("php://input"), $in); // JSON body could not be parsed, throw exception if ($in === null) { throw new HTTPException('There was a problem understanding the data sent to the server by the application.', 409, array('dev' => 'The JSON body sent to the server was unable to be parsed.', 'internalCode' => 'REQ1000', 'more' => '')); } return $in; }); }
return new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname)); }); $di->set('dispatcher', function () use($di) { $dispatcher = new Phalcon\Mvc\Dispatcher(); return $dispatcher; }); $di->set('hash', function () { $hash = new \Phalcon\Security(); //Set the password hashing factor to 12 rounds $hash->setWorkFactor(12); return $hash; }, true); $di->setShared('db', function () use($di, $config) { // Events Manager para la base de datos $eventsManager = new \Phalcon\Events\Manager(); $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config->database->toArray()); $connection->setEventsManager($eventsManager); return $connection; }); $di->set('modelsManager', function () { return new \Phalcon\Mvc\Model\Manager(); }); $di->set('logger', function () { // Archivo de log return new \Phalcon\Logger\Adapter\File("../app/logs/debug.log"); }); $urlManager = new \Silar\Misc\UrlManager($config); $di->set('urlManager', $urlManager); $di->set('flashSession', function () { $flash = new \Phalcon\Flash\Session(array('error' => 'alert alert-danger text-center', 'success' => 'alert alert-success text-center', 'notice' => 'alert alert-info text-center', 'warning' => 'alert alert-warning text-center')); return $flash;
/** * Mount the module specific routes before the module is loaded. * Add ModuleRoutes Group and annotated controllers for parsing their routing information. * * @param \Phalcon\DiInterface $di */ public static function initRoutes(DiInterface $di) { $loader = new Loader(); $loader->registerNamespaces(['App\\Modules\\Backend\\Controllers' => __DIR__ . '/Controllers/', 'App\\Modules\\Backend\\Controllers\\API' => __DIR__ . '/Controllers/api/', 'App\\Modules\\Backend\\Models' => __DIR__ . '/Models/', 'App\\Modules\\Backend\\Library' => __DIR__ . '/Lib/', 'App\\Modules\\Frontend\\Controllers' => __DIR__ . '/../Frontend/Controllers/', 'App\\Modules\\Frontend\\Models' => __DIR__ . '/../Frontend/Models/'], TRUE)->register(); /** * Read application wide and module only configurations */ $appConfig = $di->get('config'); $moduleConfig = (include __DIR__ . '/config/config.php'); $di->setShared('moduleConfig', $moduleConfig); /** * The URL component is used to generate all kind of urls in the application */ $di->setShared('url', function () use($appConfig) { $url = new UrlResolver(); $url->setBaseUri($appConfig->application->baseUri); return $url; }); $di->setShared('request', function () use($appConfig) { return new \Phalcon\Http\Request(); }); /** * Read configuration */ include __DIR__ . "/../../config/env/" . $appConfig->application->environment . ".php"; $database = $di->getConfig()->application->site . $di->get('request')->getQuery("countryCode"); /** * Module specific database connection */ $di->set('db', function () use($config, $database) { $eventsManager = new \Phalcon\Events\Manager(); //Create a database listener $dbListener = new MyDBListener(); //Listen all the database events $eventsManager->attach('db', $dbListener); $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(['host' => $config->{$database}->host, 'username' => $config->{$database}->username, 'password' => $config->{$database}->password, 'dbname' => $config->{$database}->dbname, 'options' => array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'")]); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); return $connection; }); /** * Simple database connection to localhost */ $di->set('mongo', function () use($config, $database) { $mongo = new \MongoClient(); return $mongo->selectDb($config->{$database}->dbname); }, true); $di->set('collectionManager', function () { return new \Phalcon\Mvc\Collection\Manager(); }, true); /** * Include composer autoloader */ require __DIR__ . "/../../../vendor/autoload.php"; /** * Module specific dispatcher */ $di->set('dispatcher', function () use($di) { $dispatcher = new Dispatcher(); $dispatcher->setDefaultNamespace('App\\Modules\\Backend\\Controllers\\'); return $dispatcher; }); $di->set('utils', function () { require __DIR__ . "/../../Common/Lib/Application/Plugins/Utils.php"; $utils = new Utils(); return $utils; }); /** * If our request contains a body, it has to be valid JSON. This parses the * body into a standard Object and makes that available from the DI. If this service * is called from a function, and the request body is not valid JSON or is empty, * the program will throw an Exception. */ $di->setShared('requestBody', function () { parse_str(file_get_contents("php://input"), $in); // JSON body could not be parsed, throw exception if ($in === null) { throw new HTTPException('There was a problem understanding the data sent to the server by the application.', 409, array('dev' => 'The JSON body sent to the server was unable to be parsed.', 'internalCode' => 'REQ1000', 'more' => '')); } return $in; }); /** * This means we can create listeners that run when an event is triggered. */ $di->setShared('modelsManager', function () use($di, $config, $database) { $eventsManager = new \Phalcon\Events\Manager(); $customModelsManager = new CustomModelsManager(); /** * Attach an anonymous function as a listener for "model" events */ $eventsManager->attach('model', $customModelsManager); /** * Setting a default EventsManager */ $customModelsManager->setEventsManager($eventsManager); return $customModelsManager; }); }
$di->setShared('view', function () use($config) { $view = new Phalcon\Mvc\View\Simple(); $view->setViewsDir(ROOTDIR . '/app/views/'); $view->registerEngines(array('.phtml' => function ($view) use($config) { $volt = new Phalcon\Mvc\View\Engine\Volt($view); $volt->setOptions(array('compiledPath' => ROOTDIR . '/tmp/volt/', 'compiledExtension' => '.php', 'compiledSeparator' => '_', 'compileAlways' => true)); $compiler = $volt->getCompiler(); $compiler->addFunction('recaptcha_get_html', function () use($config) { return "'" . recaptcha_get_html($config->captcha->pub, null, true) . "'"; }); return $volt; })); return $view; }); $di->setShared('db', function () use($config) { $db = new \Phalcon\Db\Adapter\Pdo\Mysql($config->db->toArray()); $db->execute('SET NAMES UTF8', array()); return $db; }); $di->setShared('modelsMetadata', function () use($config) { if ($config->app->cache_apc) { $metaData = new Phalcon\Mvc\Model\MetaData\Apc(array("lifetime" => 3600, "prefix" => $config->app->suffix . "-meta-db-main")); } else { $metaData = new \Phalcon\Mvc\Model\Metadata\Files(array('metaDataDir' => ROOTDIR . '/tmp/cache/')); } return $metaData; }); $di->setShared('crypt', function () { return new Phalcon\Crypt(); }); $di->setShared('security', function () {
<li> <a href="#">Classement</a> </li> <li> <a href="#">Joueurs</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li> <a href="#">Admin</a> </li> </ul> </div> </nav> <div class="atp-title"><h1>ATP</h1><h5>Phalcon MVC Application</h5></div> <div> <?php $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array('host' => 'localhost', 'dbname' => 'atp', 'username' => 'root', 'password' => 'Flocon123', 'options' => [PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_PERSISTENT => TRUE])); $result = $connection->query("SELECT * FROM joueur"); $result->setFetchMode(Phalcon\Db::FETCH_NUM); echo "<table class='table'><th>Flag</th><th>Nom</th><th>Prénom</th><th>Code Pays</th>"; while ($joueur = $result->fetch()) { echo "<tr><td class='flag'></td><td>{$joueur['2']}</td>"; echo "<td>{$joueur['1']}</td>"; echo "<td>{$joueur['3']}</td></tr>"; } echo "</table>"; ?> </div>
public function testDbMysql() { require 'unit-tests/config.db.php'; if (empty($configMysql)) { $this->markTestSkipped("Skipped"); return; } $connection = new Phalcon\Db\Adapter\Pdo\Mysql($configMysql); //List tables $expectedTables = array(0 => 'albums', 1 => 'artists', 2 => 'customers', 3 => 'm2m_parts', 4 => 'm2m_robots', 5 => 'm2m_robots_parts', 6 => 'parts', 7 => 'personas', 8 => 'personnes', 9 => 'prueba', 10 => 'robots', 11 => 'robots_parts', 12 => 'songs', 13 => 'subscriptores', 14 => 'tipo_documento'); $tables = $connection->listTables(); $this->assertEquals($tables, $expectedTables); $tables = $connection->listTables('phalcon_test'); $this->assertEquals($tables, $expectedTables); //Table exist $this->assertEquals($connection->tableExists('personas'), 1); $this->assertEquals($connection->tableExists('noexist'), 0); $this->assertEquals($connection->tableExists('personas', 'phalcon_test'), 1); $this->assertEquals($connection->tableExists('personas', 'test'), 0); $expectedDescribe = $this->getExpectedColumnsMysql(); $describe = $connection->describeColumns('personas'); $this->assertEquals($describe, $expectedDescribe); $describe = $connection->describeColumns('personas', 'phalcon_test'); $this->assertEquals($describe, $expectedDescribe); //Table Options $expectedOptions = array('table_type' => 'BASE TABLE', 'auto_increment' => NULL, 'engine' => 'InnoDB', 'table_collation' => 'utf8_unicode_ci'); $options = $connection->tableOptions('personas', 'phalcon_test'); $this->assertEquals($options, $expectedOptions); //Indexes $expectedIndexes = array('PRIMARY' => Phalcon\Db\Index::__set_state(array('_indexName' => 'PRIMARY', '_columns' => array('id'))), 'robots_id' => Phalcon\Db\Index::__set_state(array('_indexName' => 'robots_id', '_columns' => array('robots_id'))), 'parts_id' => Phalcon\Db\Index::__set_state(array('_indexName' => 'parts_id', '_columns' => array('parts_id')))); $describeIndexes = $connection->describeIndexes('robots_parts'); $this->assertEquals($describeIndexes, $expectedIndexes); $describeIndexes = $connection->describeIndexes('robots_parts', 'phalcon_test'); $this->assertEquals($describeIndexes, $expectedIndexes); //References $expectedReferences = array('robots_parts_ibfk_1' => Phalcon\Db\Reference::__set_state(array('_referenceName' => 'robots_parts_ibfk_1', '_referencedTable' => 'robots', '_columns' => array('robots_id'), '_referencedColumns' => array('id'), '_referencedSchema' => 'phalcon_test')), 'robots_parts_ibfk_2' => Phalcon\Db\Reference::__set_state(array('_referenceName' => 'robots_parts_ibfk_2', '_referencedTable' => 'parts', '_columns' => array('parts_id'), '_referencedColumns' => array('id'), '_referencedSchema' => 'phalcon_test'))); $describeReferences = $connection->describeReferences('robots_parts'); $this->assertEquals($describeReferences, $expectedReferences); $describeReferences = $connection->describeReferences('robots_parts', 'phalcon_test'); $this->assertEquals($describeReferences, $expectedReferences); }
/** * Set the database service * @return void */ protected function db() { $config = $this->_config; $profiler = $this->profiler(); //@todo get this sodding profiler working $this->_di->set('db', function () use($config, $profiler) { $eventsManager = new \Phalcon\Events\Manager(); // Listen to all database events $eventsManager->attach('db', function ($event, $connection) use($profiler) { /*$profiler = new \Phalcon\Db\Profiler(); //var_dump($profiler); exit; if ($event->getType() == 'beforeQuery') { $profiler->startProfile($connection->getSQLStatement()); } if ($event->getType() == 'afterQuery') { $profiler->stopProfile(); }*/ }); $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname, "options" => array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'))); $connection->setEventsManager($eventsManager); return $connection; }); }
protected function _getDI() { Phalcon\DI::reset(); $di = new Phalcon\DI(); $di->set('modelsManager', function () { return new Phalcon\Mvc\Model\Manager(); }); $di->set('modelsMetadata', function () { return new Phalcon\Mvc\Model\Metadata\Memory(); }); $di->set('db', function () { require 'unit-tests/config.db.php'; //return new Twm\Db\Adapter\Pdo\Mssql($configMssql); $connection = new Phalcon\Db\Adapter\Pdo\Mysql($configMysql); $eventsManager = new Phalcon\Events\Manager(); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) { if ($event->getType() == 'beforeQuery') { echo $connection->getSQLStatement(); } }); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); return $connection; }); return $di; }