/** * Tests Mysql::escapeIdentifier * * @author Sid Roberts <*****@*****.**> * @since 2016-11-19 */ public function testEscapeIdentifier() { $this->specify('Identifiers are not properly escaped', function ($identifier, $expected) { $escapedIdentifier = $this->connection->escapeIdentifier($identifier); expect($escapedIdentifier)->equals($expected); }, ["examples" => [["identifier" => "robots", "expected" => "`robots`"], ["identifier" => ["schema", "robots"], "expected" => "`schema`.`robots`"], ["identifier" => "`robots`", "expected" => "```robots```"], ["identifier" => ["`schema`", "rob`ots"], "expected" => "```schema```.`rob``ots`"]]]); }
/** * 登録メソッド * * @param array ユーザー情報 * @return boolean 結果 */ public function insert($params) { $sql = 'INSERT INTO ' . 'users ' . 'SET ' . 'phone_number = :phone_number, ' . 'name = :name, ' . 'created = :created '; $statement = $this->_dbCon->prepare($sql); $result = $statement->execute(['phone_number' => $params['phoneNumber'], 'name' => $params['name'], 'created' => $params['created']]); return $result; }
/** * Tests Mysql::listTables * * @author Serghei Iakovlev <*****@*****.**> * @since 2016-08-03 */ public function testListTables() { $this->specify('Mysql::listTables does not return correct result', function () { $expected = ['albums', 'artists', 'childs', 'customers', 'issue12071_body', 'issue12071_head', 'issue_11036', 'issue_1534', 'issue_2019', 'm2m_parts', 'm2m_robots', 'm2m_robots_parts', 'package_details', 'packages', 'parts', 'personas', 'personnes', 'ph_select', 'prueba', 'robots', 'robots_parts', 'songs', 'subscriptores', 'tipo_documento', 'users']; expect($this->connection->listTables())->equals($expected); expect($this->connection->listTables(TEST_DB_MYSQL_NAME))->equals($expected); }); }
/** * Registers the module-only services * * @param Phalcon\DI $di */ public function registerServices($di) { /** * Read configuration */ $config = (include __DIR__ . "/config/config.php"); $di['view']->setViewsDir(__DIR__ . '/views/'); /** * Database connection is created based in the parameters defined in the configuration file */ $di['db'] = function () use($config) { $connection = new DbAdapter(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname)); $eventsManager = new EventsManager(); $logger = new FileLogger(__DIR__ . "/logs/db.log"); //Listen all the database events $eventsManager->attach('db:beforeQuery', function ($event, $connection) use($logger) { $sqlVariables = $connection->getSQLVariables(); if (count($sqlVariables)) { $logger->log($connection->getSQLStatement() . ' ' . join(', ', $sqlVariables), Logger::INFO); } else { $logger->log($connection->getSQLStatement(), Logger::INFO); } }); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); return $connection; }; }
public function createDb() { if (!$this->_dbExist) { $mysqli = new \mysqli($this->_mDescriptor['host'], $this->_mDescriptor['username'], $this->_mDescriptor['password']); if ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } $this->_mHostInfo = $mysqli->host_info; $sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->_mDescriptor['dbname']; if (!$mysqli->query($sql)) { $mysqli->close(); die("DB creation failed: (" . $mysqli->errno . ") " . $mysqli->error); } $mysqli->close(); $this->_dbExist = true; parent::__construct($this->_mDescriptor); } }
private function setDB() { $connection = new DatabaseConnection($this->database->toArray()); $debug = $this->application->debug; if ($debug) { $eventsManager = new EventsManager(); $logger = new FileLogger(__DIR__ . "/../Logs/db.log"); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $variables = $connection->getSQLVariables(); if ($variables) { $logger->log($connection->getSQLStatement() . ' [' . join(',', $variables) . ']', \Phalcon\Logger::INFO); } else { $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); } } }); $connection->setEventsManager($eventsManager); } return $connection; }
} return $url; }, true); $di->set('tag', function () { return new reportingtool\Helper\Tag(); }); $di->set('modelsManager', function () { return new Phalcon\Mvc\Model\Manager(); }); /** * Database connection is created based in the parameters defined in the configuration file */ $di->set('db', function () use($config) { $debug = $config->application->debug; if ($debug) { $connection = new DatabaseConnection($config->database->debug->toArray()); $eventsManager = new EventsManager(); //Listen all the database events //$logger = new FileLogger(APP_PATH . "/app/logs/db.log"); $eventsManager->attach('db', function ($event, $connection) { if ($event->getType() == 'beforeQuery') { //$logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); } }); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); } else { $connection = new DatabaseConnection($config->database->production->toArray()); } return $connection; });
/** * Initializes the database * * @param array $options */ protected function initDatabase($options = array()) { $config = $this->di['config']; // setup database service $this->di['db'] = function () use($config) { $connection = new PhMysql(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname)); // log sql statements if ('1' == $config->application->debug) { $eventsManager = new EventsManager(); $logger = new PhLogFileAdapter($config->application->logDir . "/db.log"); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); } }); // Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); } return $connection; }; }
<?php /** * 修改专业热度 * User: ren * Date: 15-10-23 * Time: 下午5:11 */ header('content-type:text/html;charset=utf-8'); use Phalcon\Db\Adapter\Pdo\Mysql; $db = new Mysql(['host' => 'localhost', 'username' => 'root', 'password' => 'root', 'dbname' => 'yxk_51']); $db->execute('set names utf8'); //获取所有省份 $sql = 'select name from site_province'; $provinces = $db->fetchAll($sql); //获取所有专业id $sql = 'select maj_id from major'; $majors = $db->fetchAll($sql); //修改专业数据 $db->begin(); foreach ($majors as $val) { //格式省份数据 $tmp = array_map(function ($argc) { $argc['value'] = mt_rand(0, 100); return preg_replace('/[省市]/u', '', $argc); }, array_slice($provinces, 0, 31)); $tmp = serialize($tmp); $sql = "update major set maj_area='{$tmp}' where maj_id='{$val['maj_id']}'"; $db->execute($sql); } $db->commit();
protected function _registerServices() { $config = (include $this->appConfigDirectory . "config.php"); if (isset($config['mode'])) { self::$mode = $config->mode; } $this->di['config'] = $config; $this->di['dispatcher'] = function () { $dispatcher = new Dispatcher(); // $this->eventManager->attach('dispatch', new HttpResponsePlugin()); // // $dispatcher->setEventsManager($this->eventManager); //注册默认controller目录 $dispatcher->setDefaultNamespace('myweb\\twoweb\\Controllers\\home'); return $dispatcher; }; /** * 数据库设定, 自动读取配置中的所有数据库 */ call_user_func(function () { $logger = $this->getLogger('mysql'); $configs = (include $this->globalConfigDirectory . "mysql.php"); $configs = $configs[self::$mode]; foreach ($configs as $name => $_config) { $this->di['db.' . "{$name}"] = function () use($logger, $name, $_config) { $this->eventManager->attach('db', function ($event, $connection) use($logger, $name) { if ($event->getType() == 'beforeQuery') { // $logger->log("[$name]: " .$connection->getSQLStatement(), \Phalcon\Logger::INFO); } }); $mysql = new MysqlDB($_config); $mysql->setEventsManager($this->eventManager); return $mysql; }; } }); /** * mongodb */ call_user_func(function () { $configs = (include $this->globalConfigDirectory . "mongo.php"); $configs = $configs[self::$mode]; $logger = $this->getLogger('mongo'); foreach ($configs as $name => $_config) { $this->di['mongo' . ".{$name}"] = function () use($name, $_config) { $auth = ""; if (!empty($_config['username']) && !empty($_config['password'])) { $auth = $_config['username'] . ":" . $_config['password'] . "@"; } $connection = new MongoDB("mongodb://{$auth}{$_config['host']}:{$_config['port']}/{$_config['dbname']}"); return $connection->selectDB($_config['dbname']); }; } }); // collection log $this->di['collectionManager'] = function () { $modelsManager = new CollectionManager(); $modelsManager->setEventsManager($this->eventManager); return $modelsManager; }; $this->di->set('voltService', function ($view, $di) { $volt = new Volt($view, $di); $volt->setOptions(array('compiledPath' => APP_CACHE_PATH . "caches_template" . DIRECTORY_SEPARATOR, 'compiledExtension' => '.compiled', 'compileAlways' => false)); $compiler = $volt->getCompiler(); $compiler->addFilter('array_slice', 'array_slice'); return $volt; }); $this->di->set('view', function () { $view = new View(); $view->setViewsDir(APP_PATH . "views"); $view->registerEngines(array(".html" => 'voltService')); return $view; }, true); $this->di['router'] = function () { $router = (include $this->appConfigDirectory . "router.php"); return $router; }; $this->di['logger'] = function () { $logger = $this->getLogger("debug"); return $logger; }; $this->di['mongolog'] = function () { $logger = $this->getLogger("mongo"); return $logger; }; /** * redis 设定 */ call_user_func(function () { $configs = (include $this->globalConfigDirectory . "redis.php"); $configs = $configs[self::$mode]; foreach ($configs as $name => $_config) { $this->di->set('redis.' . $name, function () use($_config) { return $this->connectRedis($_config); }); } }); /** * 缓存设定 */ $this->di['cache'] = function () { //1 days $frontCache = new FrontCache(array('lifetime' => 86400)); return new FileCache($frontCache, array('cacheDir' => APP_CACHE_PATH . "caches_data" . DIRECTORY_SEPARATOR)); }; /** * Model Cache */ $this->di['modelsCache'] = function () { return $this->di['cache']; }; $this->di['modelsMetadata'] = function () { //1 days $metaDataCache = new FileMetaData(array('lifetime' => 86400, 'metaDataDir' => APP_CACHE_PATH . "caches_metadata" . DIRECTORY_SEPARATOR)); return $metaDataCache; }; }
<?php /** * Created by PhpStorm. * User: ren * Date: 15-11-4 * Time: 下午4:44 */ use Phalcon\Db\Adapter\Pdo\Sqlite; use Phalcon\Db\Adapter\Pdo\Mysql; header('content-type:text/html;charset=utf-8'); $mysql = new Mysql(['host' => 'localhost', 'username' => 'root', 'password' => 'root', 'dbname' => 'yxk_51']); $mysql->execute('set names utf8'); //大学大专高职数据 $mysql->execute("update college set city_code=340100 where city_code=341400"); //巢湖并入合肥,县级 $mysql->execute("update school set city_code=340100 where city_code=341400"); //巢湖并入合肥,县级 $mysql->execute("update college set city_code=654000 where city_code=654200"); //塔城地区归伊犁哈萨克自治州统辖 $mysql->execute("update school set city_code=654000 where city_code=654200"); //塔城地区归伊犁哈萨克自治州统辖 $mysql->execute("update college set city_code=654000 where city_code=654300"); //阿勒泰地区归伊犁哈萨克自治州统辖 $mysql->execute("update school set city_code=654000 where city_code=654300"); //阿勒泰地区归伊犁哈萨克自治州统辖 $mysql->execute("update school set city_code=520600 where city_code=522200"); //铜仁地区撤销,改为铜仁市 $mysql->execute("update school set city_code=520500 where city_code=522400"); //毕节地区撤销,改为毕节市 $mysql->execute("update school set city_code=630200 where city_code=632100");
/** * Registers services related to the module * * @param DiInterface $di */ public function registerServices(DiInterface $di) { $config = $this->config; $debug = $this->debug; /** * Setting up the view component */ $DD = $this::DIR; $di['view'] = function () use($config, $debug, $DD) { $view = new View(); $viewDir = $DD . '/views/'; if ($config->offsetExists('application') && $config->application->offsetExists('viewsDir') && $config->application->offsetExists('viewsDir')) { $viewDir = $config->application->viewsDir; } $view->setViewsDir($viewDir); $viewEngines = ['.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']; $viewEngines['.volt'] = function ($view, $di) use($config, $debug, $DD) { $cacheDir = $DD . '/../cache/'; $appConfig = $di['appConfig']; if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('cacheDir')) { $cacheDir = $appConfig->volt->cacheDir; } elseif ($config->offsetExists('application') && $config->application->offsetExists('cacheDir') && $config->application->offsetExists('cacheDir')) { $cacheDir = $config->application->cacheDir; } $volt = new VoltEngine($view, $di); $volt->setOptions(array('compiledPath' => $cacheDir, 'compiledExtension' => ".compiled", 'compiledSeparator' => '_', 'compileAlways' => $debug)); $compiler = $volt->getCompiler(); // 扩展 if ($config->offsetExists('volt') && $config->volt->offsetExists('extension')) { foreach ($config->volt->extension as $k => $v) { $compiler->addExtension($v); } } if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('extension')) { foreach ($appConfig->volt->extension as $k => $v) { $compiler->addExtension($v); } } // 函数 if ($config->offsetExists('volt') && $config->volt->offsetExists('func')) { foreach ($config->volt->func as $k => $v) { $compiler->addFunction($k, $v); } } if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('func')) { foreach ($appConfig->volt->func as $k => $v) { $compiler->addFunction($k, $v); } } // 过滤器 if ($config->offsetExists('volt') && $config->volt->offsetExists('filter')) { foreach ($config->volt->filter as $k => $v) { $compiler->addFilter($k, $v); } } if ($appConfig->offsetExists('volt') && $appConfig->volt->offsetExists('filter')) { foreach ($appConfig->volt->filter as $k => $v) { $compiler->addFilter($k, $v); } } return $volt; }; $view->registerEngines($viewEngines); return $view; }; if ($config->offsetExists('database')) { $di['db'] = function () use($config, $di, $debug) { $appConfig = $di['appConfig']; if ($debug && $appConfig->offsetExists('logger') && $appConfig->logger->offsetExists('sqlPath')) { $eventsManager = new EventsManager(); $path = $config->logger->sqlPath; $path = str_replace('{{date}}', date("Ymd"), $path); $logger = new LoggerFile($path); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), Logger::INFO); } }); $connection = new DbAdapter($config->database->toArray()); //Assign the eventsManager to the db adapter instance $connection->setEventsManager($eventsManager); return $connection; } else { return new DbAdapter($config->database->toArray()); } }; } if ($config->offsetExists('application') && $config->application->offsetExists('baseUri')) { $di['url'] = function () use($config) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($config->application->baseUri); return $url; }; } $di['moduleConfig'] = function () use($config) { return $config; }; }
/** * set the database connection under db */ protected function initDatabase() { $config = $this->di->get('config'); $logger = $this->di->get('logger'); $debug = isset($config->app->debug) ? (bool) $config->app->debug : false; $this->di->set('db', function () use($config, $debug, $logger) { $params = ['host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->name]; $connection = new PhDbAdapter($params); if ($debug) { $eventsManager = new PhEventsManager(); $eventsManager->attach('db', function (PhEvent $event, PhDbAdapter $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), PhLogger::INFO); } }); $connection->setEventsManager($eventsManager); } return $connection; }); }
protected function initDb() { $di = $this->getDi(); // Setup the database service $di->set('db', function () { $config = $this->getConfig()['database']; $eventsManager = new EventsManager(); $logger = new FileLogger(ROOT . $this->getConfig()['apps_data']['tmp_path'] . '/' . date('Y-m-d') . '.sql.log'); // Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->info($connection->getSQLStatement()); } }); $db = new \Phalcon\Db\Adapter\Pdo\Mysql($config); // $db->query('set names utf-8'); $db->setEventsManager($eventsManager); return $db; }); }
private static function registCommonService($di, $config) { $di->setShared('config', $config); $di->setShared('profiler', function () { return new \Phalcon\Db\Profiler(); }); $di->setShared('modelsMetadata', function () use($di, $config) { if ('file' == $config->metaData->saveType) { $savePath = $config->metaData->savePath; if (!file_exists($savePath)) { mkdir($savePath, 0744, true); } $metaData = new \Phalcon\Mvc\Model\Metadata\Files(array('metaDataDir' => $savePath)); return $metaData; } }); $di->setShared('db_myPhalcon_w', function () use($di, $config) { $profiler = $di->getProfiler(); $eventsManager = new \Phalcon\Events\Manager(); $eventsManager->attach('db', function ($event, $connection) use($profiler) { if ($event->getType() == 'beforeQuery') { $profiler->startProfile($connection->getSQLStatement(), $connection->getSqlVariables(), $connection->getSQLBindTypes()); } if ($event->getType() == 'afterQuery') { $profiler->stopProfile(); $profile = $profiler->getLastProfile(); LoggerUtil::info(sprintf('SQL %s , cost time : %s', $profile->getSQLStatement(), $profile->getTotalElapsedSeconds())); } }); $db = new DbAdapter(array('host' => $config->mysql->myPhalcon_w->host, 'username' => $config->mysql->myPhalcon_w->username, 'password' => $config->mysql->myPhalcon_w->password, 'dbname' => $config->mysql->myPhalcon_w->dbname, 'port' => $config->mysql->myPhalcon_w->port)); $db->setEventsManager($eventsManager); return $db; }); $di->setShared('db_myPhalcon_r', function () use($di, $config) { $profiler = $di->getProfiler(); $eventsManager = new \Phalcon\Events\Manager(); $eventsManager->attach('db', function ($event, $connection) use($profiler) { if ($event->getType() == 'beforeQuery') { $profiler->startProfile($connection->getSQLStatement(), $connection->getSqlVariables(), $connection->getSQLBindTypes()); } if ($event->getType() == 'afterQuery') { $profiler->stopProfile(); $profile = $profiler->getLastProfile(); LoggerUtil::info(sprintf('SQL: %s , COST TIME: %s', $profile->getSQLStatement(), $profile->getTotalElapsedSeconds())); } }); $db = new DbAdapter(array('host' => $config->mysql->myPhalcon_r->host, 'username' => $config->mysql->myPhalcon_r->username, 'password' => $config->mysql->myPhalcon_r->password, 'dbname' => $config->mysql->myPhalcon_r->dbname, 'port' => $config->mysql->myPhalcon_r->port)); $db->setEventsManager($eventsManager); return $db; }); $di->setShared('redisCache', function () use($di, $config) { require VENDOR_PATH . '/predis/Autoloader.php'; \Predis\Autoloader::register(); $host = $config->redisCache->host; $port = $config->redisCache->port; return new \Predis\Client("tcp://{$host}:{$port}"); }); $di->setShared('curl', function () use($di, $config) { require VENDOR_PATH . '/Curl/Autoloader.php'; \Curl\Autoloader::register(); return new \Curl\Curl(); }); $di->setShared('image', function () use($di, $config) { require VENDOR_PATH . '/Image/Autoloader.php'; \Image\Autoloader::register(); return new \Image\Image(\Image\Image::IMAGE_IMAGICK); }); }
/** * Checks if a table exists * * @param string $tableName * @param string $schemaName * @return boolean */ public function tableExists($tableName, $schemaName = null) { $this->_connect(); return parent::tableExists($tableName, $schemaName); }
return $logger; }; /** * DATABASE */ $di['db'] = function () use($config, $di) { $logger = $di['logger']; $eventsManager = new PhEventsManager(); // Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), PhLogger::INFO); } }); $params = ["host" => $config->app_db->host, "username" => $config->app_db->username, "password" => $config->app_db->password, "dbname" => $config->app_db->name, "charset" => 'utf8']; $conn = new PhMysql($params); // Set everything to UTF8 $conn->execute('SET NAMES UTF8', []); $conn->setEventsManager($eventsManager); return $conn; }; /** * If the configuration specify the use of metadata adapter use it * or use memory otherwise */ $di['modelsMetadata'] = function () use($config) { $metaData = new PhMetadataFiles(['metaDataDir' => ROOT_PATH . $config->app_model->metadata]); //Set a custom meta-data database introspection $metaData->setStrategy(new FlyAnnotationsMetaDataInitializer()); return $metaData; };
<?php /** * 修改幼儿园,小学,初中,高中热度 * User: ren * Date: 15-10-23 * Time: 上午11:31 */ use Phalcon\Db\Adapter\Pdo\Mysql; $db = new Mysql(['host' => 'localhost', 'username' => 'root', 'password' => 'root', 'dbname' => 'yxk_51']); //修改幼儿园,小学,初中,高中热度 $sql = 'select sch_id,public_type,sch_logo,sch_thumb from school'; $school = $db->fetchAll($sql); $basic = 1; $db->begin(); foreach ($school as $key => $val) { //公办,基本点击率+1 if ($val['public_type'] > 0) { $basic += 1; } //有logo图片,基本点击率+1 if ($val['sch_logo']) { $basic += 1; } //有缩略图,基本点击率+1 if ($val['sch_thumb']) { $basic += 2; } $click = $basic * mt_rand(80, 100); $hot = $click * mt_rand(5, 9) + mt_rand(0, 10); //修改热度
$di->setShared('db', function () use($config) { $db = new DbAdapter(['host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname, 'charset' => $config->database->charset, 'persistent' => $config->database->persistent, 'options' => [PDO::ATTR_TIMEOUT => 1]]); if ($config->debug) { $eventsManager = new EventsManager(); $logger = new FileLogger(PROJ_DIR . '/common/logs/debug.log'); $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), Logger::INFO); } }); $db->setEventsManager($eventsManager); } return $db; }); $di->setShared('dbSlave', function () use($config) { $db = new DbAdapter(['host' => $config->db->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname, 'charset' => $config->database->charset, "options" => [PDO::ATTR_TIMEOUT => "1"]]); if ($config->debug) { $eventsManager = new EventsManager(); $logger = new FileLogger(PROJ_DIR . '/common/logs/debug.log'); $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), Logger::INFO); } }); $db->setEventsManager($eventsManager); } return $db; }); /** * /** * debug模式不缓存
/** * Calling the parent execute method in PDO class * * @param String $sqlStatement * @param array $bindParams * @param array $bindTypes * * @return bool|\Phalcon\Db\ResultInterface */ protected function callParentQuery($sqlStatement, $bindParams, $bindTypes) { return parent::query($sqlStatement, $bindParams, $bindTypes); }
/** * * @param type $options */ protected function initDatabase($options = []) { $config = $this->_di->get('config'); $databases = $this->_di->get('databases'); $logger = $this->_di->get('loggerDb'); $environment = $config->application->environment != 'production' ? true : false; foreach ($databases->database as $key => $value) { $this->_di->setShared($key, function () use($value, $logger, $environment, $key) { if ($environment) { $eventsManager = new EventsManager(); $dbListener = new DbListener(); $eventsManager->attach($key, $dbListener); } $params = ['host' => $value->host, 'username' => $value->username, 'password' => $value->password, 'dbname' => $value->dbname, 'schema' => $value->schema, 'charset' => $value->charset, 'options' => [PDO::ATTR_PERSISTENT => TRUE, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING]]; switch ($value->adapter) { case 'Oracle': $conn = new Oracle($params); $params['options'][PDO::ATTR_CASE] = PDO::CASE_UPPER; break; case 'Mysql': $conn = new Mysql($params); break; } if ($environment) { $conn->setEventsManager($eventsManager); } return $conn; }); } $this->_di->setShared('modelsMetadata', function () use($config) { if (isset($config->model->metadata->on) && $config->model->metadata->on) { if ($config->model->metadata->adapter == 'Files') { if (!file_exists($config->model->metadata->path)) { mkdir($config->model->metadata->path, 0777, true); } $modelsMetadata = new MetadataFiles(['metaDataDir' => $config->model->metadata->path]); return $modelsMetadata; } if ($config->model->metadata->adapter == 'Apc') { $modelsMetadata = new MetadataApc(array('prefix' => 'mpe-intranet-', 'lifetime' => 86400)); return $modelsMetadata; } else { return new MetadataMemory(); } } else { return new MetadataMemory(); } }); $this->_di->setShared('modelsManager', function () { return new ModelsManager(); }); }
protected function initDb() { $config = $this->di['config']; $profiler = $this->di['profiler']; $this->di->set('db', function () use($config, $profiler) { // set up the database adapter $adapter = new DbAdapter(['host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname, 'persistent' => $config->database->persistent]); if ($config->profiling->query) { $eventsManager = new \Phalcon\Events\Manager(); // listen to all the database events $eventsManager->attach('db', function ($event, $connection) use($profiler) { if ($event->getType() == 'beforeQuery') { $profiler->startProfile($connection->getSQLStatement()); } if ($event->getType() == 'afterQuery') { $profiler->stopProfile(); } }); $adapter->setEventsManager($eventsManager); } return $adapter; }, TRUE); }
return $volt; }, true); /** * Setting up the view component */ $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines([".volt" => 'volt']); return $view; }, true); /** * Database connection is created based in the parameters defined in the configuration file */ $di->set('db', function () use($config, $di) { $connection = new DatabaseConnection($config->database->toArray()); $eventsManager = new EventsManager(); // Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($di) { /** @var Phalcon\Events\Event $event */ if ($event->getType() == 'beforeQuery') { /** @var DatabaseConnection $connection */ $variables = $connection->getSQLVariables(); $string = $connection->getSQLStatement(); if ($variables) { $string .= ' [' . join(',', $variables) . ']'; } // To disable logging change logLevel in config $di->get('logger', ['db.log'])->debug($string); } });
public static function load(&$di, &$config) { /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }, true); /** * Setting up the view component */ $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); return $view; }, true); /** * Database connection is created based in the parameters defined in the configuration file */ $di->set('db', function () use($config) { $db = new DbAdapter((array) $config->database); $db->timeout = $config->database->timeout; $db->start = time(); $eventsManager = new \Phalcon\Events\Manager(); $eventsManager->attach('db', function ($event, $db) { if ($event->getType() == 'beforeQuery') { $idle = time() - $db->start; if ($idle > $db->timeout) { $db->connect(); $db->start = time(); } } return true; }); return $db; }); /** * If the configuration specify the use of metadata adapter use it or use memory otherwise */ $di->set('modelsMetadata', function () { return new MetaDataAdapter(); }); /** * Start the session the first time some component request the session service */ $di->set('session', function () { $session = new SessionAdapter(); $session->start(); return $session; }); /** * Set encryption */ $di->set('crypt', function () { $crypt = new Phalcon\Crypt(); $crypt->setKey('&fhm8.2$m62$/,1@'); return $crypt; }, true); /** * Set security component to validate / generate tokens */ $di->set('secure', function () { return new SecurityComponent(); }); }
/** * 默认服务依赖注入 * */ protected function commonServices() { $mode = $this->mode; $di = $this->mode === 'CLI' ? new Cli() : new FactoryDefault(); // 日志 $di->set('logger', function () { $config = load('logger'); $adapter = $config['adapter']; $filename = $config[$adapter]['filename']; $filedir = dirname($filename); if (empty($config)) { throw new \Exception('logger config Require failed'); } if (!is_dir($filedir)) { mkdir($filedir, 0755, true); } $logger = new File($filename); $formatter = new Line(null, 'Y-m-d H:i:s'); $loglevel = config('app.loglevel'); $logger->setFormatter($formatter); $logger->setLogLevel($loglevel ? $loglevel : \Phalcon\Logger::ERROR); return $logger; }, true); $this->application->setDI($di); // 命名空间 $di->set('dispatcher', function () use($mode) { $dispatcher = new Dispatcher(); $dispatcher = $mode === 'CLI' ? new \Phalcon\CLI\Dispatcher() : new Dispatcher(); $bootstrap = load('bootstrap'); $default = $bootstrap['dispatcher']; $dispatcher->setDefaultNamespace($mode === 'CLI' ? $default['cli'] : $default['default']); return $dispatcher; }, true); // 路由 if ($load = load('router', null, true)) { if ($load instanceof Router) { $di->set('router', $load); } } // 视图 $di->set('view', function () { $view = new View(); $view->setViewsDir(APP_VIEW); return $view; }, true); // 加解密 if ($config = config('crypt')) { $di->set('crypt', function () use($config) { $crypt = new Crypt(); $crypt->setKey($config['authkey']); return $crypt; }, true); } // 默认缓存 if ($config = config('cache')) { $di->set('cache', function () use($config) { $cache = null; $adapter = strtolower($config['adapter']); $options = $config[$adapter]; $frontend = new Data(array('lifetime' => $config['lifetime'])); switch ($adapter) { case 'memcache': $cache = new Memcache($frontend, $options); break; case 'redis': if (empty($options['auth'])) { unset($options['auth']); } $cache = new \Phalcon\Extend\Cache\Backend\Redis($frontend, $options); break; } return $cache; }, true); } // Cookies if ($config = config('cookies')) { $di->set('cookies', function () use($config) { $cookies = new \Phalcon\Extend\Http\Response\Cookies($config); if (!config('crypt.authkey')) { $cookies->useEncryption(false); } return $cookies; }, true); } // Session if ($config = config('session')) { $di->set('session', function () use($config) { if (!empty($config['options'])) { foreach ($config['options'] as $name => $value) { ini_set("session.{$name}", $value); } } $adapter = strtolower($config['adapter']); $options = $config[$adapter]; switch ($adapter) { case 'memcache': $session = new SessionMemcache($options); break; case 'redis': $session = new \Phalcon\Extend\Session\Adapter\Redis($options); break; default: $session = new SessionFiles(); break; } $session->start(); return $session; }, true); } // Db if ($config = config('db')) { $di->set('db', function () use($config) { $mysql = new Mysql($config); if (debugMode()) { $eventsManager = new Manager(); $logger = new File(APP_LOG . DS . 'Mysql' . LOGEXT); $formatter = new Line(null, 'Y-m-d H:i:s'); $logger->setFormatter($formatter); $eventsManager->attach('db', function ($event, $mysql) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($mysql->getSQLStatement(), Logger::INFO); } if ($event->getType() == 'afterQuery') { } }); $mysql->setEventsManager($eventsManager); } return $mysql; }, true); } // DB 元信息 if ($config = config('metadata')) { $di->set('modelsMetadata', function () use($config) { $modelsMetadata = null; $adapter = strtolower($config['adapter']); $options = $config[$adapter]; switch ($adapter) { case 'memcache': $modelsMetadata = new MetaDataMemcache($options); break; case 'redis': if (empty($options['auth'])) { unset($options['auth']); } $modelsMetadata = new MetaDataRedis($options); break; } return $modelsMetadata; }, true); } $this->application->setDI($di); }
<?php /** * 修改大学,大专,高职热度 * User: ren * Date: 15-10-23 * Time: 上午11:31 */ use Phalcon\Db\Adapter\Pdo\Mysql; $db = new Mysql(['host' => 'localhost', 'username' => 'root', 'password' => 'root', 'dbname' => 'yxk_51']); //修改大学,大专,高职热度 $sql = 'select col_id,col_type,public_type,col_rank,col_logo,col_thumb from college'; $college = $db->fetchAll($sql); $basic = 1; $db->begin(); foreach ($college as $key => $val) { //本科,基本点击率+1 if ($val['col_type'] == 1) { $basic += 1; } //公办,基本点击率+1 if ($val['public_type'] == 1) { $basic += 1; } //有logo图片,基本点击率+1 if ($val['col_logo']) { $basic += 1; } //有缩略图,基本点击率+1 if ($val['col_thumb']) { $basic += 1;
/** * Initializes the database and netadata adapter * * @param array $options */ protected function initDatabase($options = array()) { $config = $this->_di->get('config'); $logger = $this->_di->get('logger'); $debug = isset($config->app->debug) ? (bool) $config->app->debug : false; $this->_di->set('db', function () use($debug, $config, $logger) { if ($debug) { $eventsManager = new PhEventsManager(); // Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), PhLogger::INFO); } }); } $params = array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name); $conn = new PhMysql($params); if ($debug) { // Assign the eventsManager to the db adapter instance $conn->setEventsManager($eventsManager); } return $conn; }); /** * If the configuration specify the use of metadata adapter use it or use memory otherwise */ $this->_di->set('modelsMetadata', function () use($config) { if (isset($config->app->metadata)) { if ($config->app->metadata->adapter == 'Files') { return new PhMetadataFiles(array('metaDataDir' => $config->app->metadata->path)); } else { return new PhMetadataMemory(); } } else { return new PhMetadataMemory(); } }); $test = $this->_di->get('modelsMetadata'); }
/** * @param $event * @param Mysql $connection */ public function afterQuery($event, Mysql $connection) { $this->logger->log($connection->getSQLStatement(), \Phalcon\Logger::ERROR); }
$di->set('url', function () use($config) { $url = new UrlResolver(); if (!$config->application->debug) { $url->setBaseUri($config->application->production->baseUri); $url->setStaticBaseUri($config->application->production->staticBaseUri); } else { $url->setBaseUri($config->application->development->baseUri); $url->setStaticBaseUri($config->application->development->staticBaseUri); } return $url; }, true); /** * Database connection is created based in the parameters defined in the configuration file */ $di->set('db', function () use($config) { $connection = new DatabaseConnection($config->database->toArray()); $debug = $config->application->debug; if ($debug) { $eventsManager = new EventsManager(); $logger = new FileLogger(APP_PATH . "/app/logs/db.log"); //Listen all the database events $eventsManager->attach('db', function ($event, $connection) use($logger) { /** @var Phalcon\Events\Event $event */ if ($event->getType() == 'beforeQuery') { /** @var DatabaseConnection $connection */ $variables = $connection->getSQLVariables(); if ($variables) { $logger->log($connection->getSQLStatement() . ' [' . join(',', $variables) . ']', \Phalcon\Logger::INFO); } else { $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); }
require 'InitFunction.php'; require 'Functions.php'; use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql; use Phalcon\Logger\Adapter\File as LoggerFile; use Phalcon\Mvc\View; use Phalcon\Mvc\View\Engine\Volt; use Phalcon\Cache\Multiple; use Phalcon\Cache\Backend\Apc as ApcCache; use Phalcon\Cache\Backend\File as FileCache; use Phalcon\Cache\Frontend\Data as DataFrontend; use Phalcon\Logger; use Phalcon\Events\Manager as EventsManager; $di = new Phalcon\DI\FactoryDefault(); //mysql $di->set("db", function () use($mysql_config) { $connection = new PdoMysql(array("host" => $mysql_config['host'], "username" => $mysql_config['username'], "password" => $mysql_config['password'], "dbname" => $mysql_config['dbname'], "options" => array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'", PDO::ATTR_CASE => PDO::CASE_LOWER))); $eventsManager = new EventsManager(); $logger = new LoggerFile(getLogFilePath(DB_LOOGER_DIR, DB_LOG_SIZE, 'db_logs_')); $eventsManager->attach('db', function ($event, $connection) use($logger) { if ($event->getType() == 'beforeQuery') { $logger->log($connection->getSQLStatement(), Logger::INFO); } }); $connection->setEventsManager($eventsManager); return $connection; }); // Logger $di->set('logger', function () { return new LoggerFile(getLogFilePath(LOOGER_DIR, LOG_SIZE, 'logs_')); }); //Router