Example #1
0
 public function perform()
 {
     try {
         $app = new Application(INI_PATH);
         $request = new RequestSimple('CLI', $this->args['module'], $this->args['controller'], $this->args['action'], $this->args['args']);
         $app->bootstrap()->getDispatcher()->dispatch($request);
     } catch (Exception $e) {
         exit(1);
     }
 }
Example #2
0
 /**
  * run worker处理方法 
  * 
  * @param string $payload 队列数据 
  * @param string $log 
  * @param string $job 任务对象
  * @param string $tube 管道对象
  * @access public
  * @return void
  */
 public function run($payload, &$log, $job, $tube)
 {
     $this->job = $job;
     $this->tube = $tube;
     try {
         // 业务逻辑代码
         // 涉及到的请求分发
         $sendRequest = new Simple('method', 'module', 'controller', 'action', $payload);
         $result = $this->app->getDispatcher()->dispatch($sendRequest);
         $result = json_decode($result->getBody(), true);
     } catch (Exception $e) {
         return 'error';
     }
 }
Example #3
0
 public static function ins($space = 'default')
 {
     //获取配置
     $config = \Yaf\Application::app()->getConfig();
     //项目名
     $projName = isset($config->projName) ? strtolower($config->projName) : 'default';
     $channel = $projName . '/' . $space;
     $channelAll = $projName . '/_all';
     if (isset(self::$ins[$channel])) {
         return self::$ins[$channel];
     }
     //日志配置
     if (!isset($config->log)) {
         throw new Exception('must config the logger first.');
     }
     $logger = new MonoLogger($space);
     $syslog = new SyslogHandler($channel, LOG_LOCAL6, self::$logLevels[$config->log->level]);
     $syslogAll = new SyslogHandler($channelAll, LOG_LOCAL6, self::$logLevels[$config->log->level]);
     //设置日志格式
     $formatter = new LineFormatter("%channel% %level_name%: %message% %context% %extra%");
     $syslog->setFormatter($formatter);
     $syslogAll->setFormatter($formatter);
     $logger->pushHandler($syslog);
     $logger->pushHandler($syslogAll);
     //增加pid
     $processor = new ProcessIdProcessor();
     $logger->pushProcessor($processor);
     //与psr3 context保持一致
     $processor = new PsrLogMessageProcessor();
     $logger->pushProcessor($processor);
     self::$ins[$channel] = $logger;
     return self::$ins[$channel];
 }
Example #4
0
 /**
  * 获取application.ini中的配置项,并转化为数组
  * @param string $name 配置名称
  * @return mix 如果没有改配置信息则返回null
  */
 public static function getConfig($name = null)
 {
     $configObj = \Yaf\Application::app()->getConfig();
     if ($name != null) {
         if (!is_array($name)) {
             $configObj = isset($configObj->{$name}) ? $configObj->{$name} : null;
         } else {
             foreach ($name as $v) {
                 if ($configObj == null) {
                     break;
                 }
                 $configObj = isset($configObj->{$v}) ? $configObj->{$v} : null;
             }
         }
     }
     if (is_object($configObj)) {
         return $configObj->toArray();
     } else {
         if (is_null($configObj)) {
             return array();
         } else {
             return $configObj;
         }
     }
 }
Example #5
0
 private function log()
 {
     $dir = APP_PATH . '/logs/request';
     if (!is_dir($dir)) {
         mkdir($dir, 0755);
     }
     $file = $dir . '/' . date('Y-m-d') . '.log';
     $logger = new \Zend_Log();
     $formatter = new \Zend_Log_Formatter_Simple("%message%\n");
     $writer = new \Zend_Log_Writer_Stream($file);
     $writer->setFormatter($formatter);
     $logger->addWriter($writer);
     $data = array();
     $data[] = '[' . date('Y-m-d H:i:s') . '] ';
     $url = Http::getUrl('current');
     $url = substr($url, 0, strpos($url, '?')) . '?' . http_build_query($this->getRequest()->getRequest());
     $data[] = $url;
     $line = implode('', $data);
     $debug = Application::app()->getConfig()->debug;
     if ($debug) {
         $res = $this->getResponse()->getBody('api');
         $line .= "\n\t" . $res;
     }
     $logger->log($line, $logger::NOTICE);
 }
Example #6
0
 public function _initTwig(Dispatcher $dispatcher)
 {
     $twig = new TwigAdapter(null, \Yaf\Application::app()->getConfig()->twig->toArray());
     $dispatcher->setView($twig);
     Yaf\Registry::set("twig", $twig);
     // $dispatcher->registerPlugin(new SmartyControllerPlugin());
 }
Example #7
0
 protected function getImgUrl($path)
 {
     if (preg_match('/^https?:\\/\\//i', $path)) {
         return $path;
     }
     return Application::app()->getConfig()->get('uploader')->get('url') . '/' . $path;
 }
Example #8
0
 public static function ins($group = null)
 {
     if (!isset($group)) {
         $group = Cache::$default;
     }
     if (isset(Cache::$instances[$group])) {
         return Cache::$instances[$group];
     }
     $allConfig = \Yaf\Application::app()->getConfig();
     $config = isset($allConfig->cache) ? $allConfig->cache->{$group} : null;
     if (!isset($config)) {
         throw new Exception('Failed to load Cache group: ' . $group);
     }
     $class = 'Cache\\Driver\\' . ucfirst($config->driver);
     if (!class_exists($class)) {
         throw new Exception('Driver ' . $class . ' not found.');
     }
     $cache = (new $class($config))->getCacheDriver();
     //获取项目名作为cache namespace
     $projName = $allConfig->projName;
     $projName = isset($projName) ? strtolower($projName) : 'default';
     $cache->setNamespace($projName);
     Cache::$instances[$group] = $cache;
     return Cache::$instances[$group];
 }
Example #9
0
 /**
  * 
  */
 function __construct()
 {
     $this->_sphinx = new SphinxClient();
     $this->_host = \Yaf\Application::app()->getConfig()->search['sphinx']['host'];
     $this->_port = intval(\Yaf\Application::app()->getConfig()->search['sphinx']['port']);
     $this->init();
 }
Example #10
0
 public function getAction()
 {
     $params = $this->getRequest()->getParams();
     $params = array_flip($params);
     $script_path = \Yaf\Application::app()->getAppDirectory() . "/../scripts/";
     $return = array();
     if (in_array('cacheprice', $params)) {
         exec("/usr/local/bin/php {$script_path}cache_price.php", $return);
     }
     if (in_array('restart', $params)) {
         exec("/usr/local/bin/php {$script_path}/../public/cli.php 'request_uri=/console/Hedge/run' > {$script_path}/../log/hedge.log 2>&1 &", $return);
     }
     if (in_array('killall', $params)) {
         exec("killall php", $return);
     }
     if (in_array('exchange', $params)) {
         $account_group_id = $this->getRequest()->getParam('account_group_id');
         $to_usd_rate = $this->getRequest()->getParam('to_usd_rate');
         $to_cny_rate = $this->getRequest()->getParam('to_cny_rate');
         $log_path = \Yaf\Application::app()->getConfig()->application->path->log . '/' . $account_group_id . '.log';
         $cli = \Yaf\Application::app()->getConfig()->application->directory . '/../public/cli.php';
         $group_id_pid = Yaf\Registry::get('redis')->get('group_id_' . $account_group_id);
         if (!empty($group_id_pid)) {
             $return[] = "group {$group_id_pid} exchange will restart";
         }
         $param = "account_group_id={$account_group_id}&to_usd_rate={$to_usd_rate}&to_cny_rate={$to_cny_rate}";
         exec('php ' . $cli . ' "request_uri=/console/Transport/exchange?' . $param . '" >> ' . $log_path . ' &');
         $return[] = 'exchange start up';
     }
     $this->getView()->assign('return', $return);
     $this->getView()->display('control.phtml');
 }
Example #11
0
 /**
  * @brief 把配置信息加载进入注册表
  * @param \Yaf\Dispatcher $dispatcher
  */
 public function _initConfig(\Yaf\Dispatcher $dispatcher)
 {
     $config = \Yaf\Application::app()->getConfig();
     foreach ($config as $section => $arrConf) {
         \Yaf\Registry::set($section, $arrConf);
     }
 }
Example #12
0
 function __construct()
 {
     $config = \Yaf\Application::app()->getConfig()->database['mysql'];
     $dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['dbname']}";
     parent::__construct($dsn, $config['user'], $config['pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES'utf8';"));
     $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 }
Example #13
0
 /**
  * 注册全局配置信息
  */
 public function _initConfig(\Yaf\Dispatcher $dispatcher)
 {
     // 获取配置文件
     $this->config = \Yaf\Application::app()->getConfig();
     \Yaf\Registry::set('config', $this->config);
     // 关闭自动加载模板
     $dispatcher->autoRender(FALSE);
 }
Example #14
0
 /**
  * 获取数据库配置项
  * @param  $name		操作的库
  */
 private static function getDbConf($name)
 {
     $conf = \Yaf\Application::app()->getConfig()->db->toArray();
     if (!empty($conf[$name]) && is_array($conf[$name])) {
         return $conf[$name];
     }
     throw new \PdoException('dbConf[' . $name . '] is not defined!');
 }
Example #15
0
 public static function getEncoding()
 {
     if (self::$encoding) {
         return self::$encoding;
     }
     self::$encoding = \Yaf\Application::app()->getConfig()->get('application')->get('encoding');
     return self::$encoding;
 }
Example #16
0
 /**
  * 构造函数,加载配置
  */
 public final function __construct()
 {
     // 读取配置
     $this->driver = new Ini(CONF_PATH . "driver.ini", Application::app()->environ());
     $this->driver = $this->driver->toArray();
     // 获取数据库对象
     $this->db = Mysql::getInstance($this->driver['mysql'][$this->adapter]);
 }
Example #17
0
 /**
  * 构造函数,获取所有模块信息并删除默认index模块
  */
 public function __construct()
 {
     $this->modules = Application::app()->getModules();
     unset($this->modules[array_search('Index', $this->modules)]);
     foreach ($this->modules as $key => $module) {
         $this->modules[$key] = strtolower($module);
     }
 }
Example #18
0
 /**
  * 导出API的api方法
  *
  * @access public
  * @param string $module 应用模块名
  * @param string $controller 对应模块内的控制器
  * @param string $action 对应控制器中的动作名
  * @param mixed $parameters 请求传递的参数
  * @return string API调用的响应正文
  */
 public function api($module, $controller, $action, $parameters)
 {
     try {
         $app = new Application(INI_PATH, 'product');
         $request = new RequestSimple('API', $module, $controller, $action, $parameters);
         $response = $app->bootstrap()->getDispatcher()->dispatch($request);
         return $response->getBody();
     } catch (Exception $e) {
         if (Application::app()->getConfig()->application->queue->log->switch) {
             $error = new ErrorLog($e, Dispatcher::getInstance()->getRequest());
             $error->errorLog();
         }
         $error = explode(ES, $e->getMessage(), 2);
         if (isset($error[1])) {
             return $error[1];
         }
     }
 }
Example #19
0
 public function __construct($path = null)
 {
     if (isset($path)) {
         $this->path = $path;
     } else {
         $config = \Yaf\Application::app()->getConfig();
         $this->path = $config['application.directory'] . '/views/';
     }
 }
Example #20
0
 /**
  * @brief 路由完成后,在这个钩子里,可以做登陆检测,权限控制等功能
  * @param \Yaf\Request_Abstract $request
  * @param \Yaf\Response_Abstract $response
  */
 public function routerShutdown(\Yaf\Request_Abstract $request, \Yaf\Response_Abstract $response)
 {
     $objConfig = \Yaf\Application::app()->getConfig();
     $arrPath = explode('/', trim($objConfig->application->baseUri, '/'));
     $strController = array_pop($arrPath);
     if (!empty($strController)) {
         $request->setControllerName($strController);
     }
 }
Example #21
0
 /**
  * 修改php.ini的默认配置
  * @param Dispatcher $dispatcher
  */
 public function _initIni(Dispatcher $dispatcher)
 {
     if ($inis = Application::app()->getConfig()->get('phpini')) {
         foreach ($inis as $prefix => $ini) {
             foreach ($ini as $suffixe => $value) {
                 ini_set("{$prefix}.{$suffixe}", $value);
             }
         }
     }
 }
Example #22
0
 /**
  * 切换视图
  * @param string $tpl 视图名称
  * @param array $tpl_vars 视图要绑定的信息
  * @return void
  */
 public function display($tpl, $tpl_vars = NULL)
 {
     // 关闭自动渲染模板
     Application::app()->getDispatcher()->disableView();
     // 公共参数信息
     $template = $this->getTemplate();
     $body = $template->render($tpl, $tpl_vars);
     // 是否需要装饰布局
     echo $template->getLayout() ? $this->decorate($body) : $body;
 }
Example #23
0
 /**
  * 注册配置文件
  */
 public function _initConfig(\Yaf\Dispatcher $dispatcher)
 {
     // 获取配置文件
     $this->config = \Yaf\Application::app()->getConfig();
     /**
      * 注册配置文件
      * 以后可以通过  Yaf\Registry::get('config') 获取
      */
     \Yaf\Registry::set('config', $this->config);
 }
Example #24
0
 public function debug($request, $response)
 {
     $config = Application::app()->getConfig()->get("xhprof")->toArray();
     if ($config and $config['debug'] == false) {
         return;
     }
     // $xhprof_data = xhprof_disable();
     $this->stop = microtime(true);
     echo ($this->stop - $this->start) * 1000 . 'ms';
     //       echo "<pre>";
     // print_r($xhprof_data);
 }
Example #25
0
 /**
  * 写入日志到日志表
  *
  * @access public
  * @param array $log
  * @return bool|int
  */
 public function add($log)
 {
     $tablename = Application::app()->getConfig()->application->queue->log->tablename;
     $table = Factory::table($tablename);
     $table->insert($log);
     $lastInsertValue = $table->getLastInsertValue();
     if ($lastInsertValue) {
         return $lastInsertValue;
     } else {
         return false;
     }
 }
Example #26
0
 /**
  * 构造函数
  */
 public function __construct()
 {
     $this->db = customSession::instance();
     $server = \Yaf\Application::app()->getConfig()->server->toArray();
     $this->lifetime = $server['sessionTime'] ? $server['sessionTime'] : 1800;
     ini_set('session.cookie_lifetime', $this->lifetime);
     ini_set('session.gc_maxlifetime', $this->lifetime);
     session_set_save_handler(array(&$this, 'open'), array(&$this, 'close'), array(&$this, 'read'), array(&$this, 'write'), array(&$this, 'destroy'), array(&$this, 'gc'));
     if (session_id() === "") {
         session_start();
     }
     // 这也是必须的,打开session,必须在session_set_save_handler后面执行
 }
Example #27
0
 /**
  * 在yaf路由分发之后响应正文之前,保存XHProf的性能统计数据
  *
  * @access public
  * @param Request_Abstract $request
  * @param Response_Abstract $response
  * @return void
  */
 public function dispatchLoopShutdown(Request_Abstract $request, Response_Abstract $response)
 {
     if (isset(Application::app()->getConfig()->application->xhprof)) {
         $xhprof_config = Application::app()->getConfig()->application->xhprof->toArray();
         if (extension_loaded('xhprof') && $xhprof_config && isset($xhprof_config['open']) && $xhprof_config['open']) {
             $namespace = $xhprof_config['namespace'] ? $xhprof_config['namespace'] : 'DefaultNameSpace';
             $xhprof_data = xhprof_disable();
             $xhprof_runs = new XHProfFiles();
             $run_id = ucfirst($request->module) . ucfirst($request->controller) . ucfirst($request->action) . '-' . str_replace('.', '', (string) microtime(true));
             $xhprof_runs->save_run($xhprof_data, $namespace, $run_id);
         }
     }
 }
Example #28
0
 /**
  * 在yaf路由分发之后响应正文之前,保存XHProf的性能统计数据
  *
  * @access public
  * @param Request_Abstract $request
  * @param Response_Abstract $response
  * @return void
  */
 public function dispatchLoopShutdown(Request_Abstract $request, Response_Abstract $response)
 {
     if (isset(Application::app()->getConfig()->application->xhprof)) {
         $xhprof_config = Application::app()->getConfig()->application->xhprof->toArray();
         if (extension_loaded('xhprof') && $xhprof_config && isset($xhprof_config['open']) && $xhprof_config['open']) {
             $namespace = $xhprof_config['namespace'] ? $xhprof_config['namespace'] : '';
             $xhprof_data = xhprof_disable();
             $xhprof_runs = new XHProfFiles();
             $run_id = ucfirst($request->module) . ucfirst($request->controller) . ucfirst($request->action) . '-' . str_replace('.', '', (string) microtime(true));
             $xhprof_runs->save_run($xhprof_data, $namespace, $run_id);
             echo "<a href='http://test.lc.com/xhprof092/xhprof_html/index.php?run={$run_id}.{$namespace}&source=xhprof'>click here</a>";
         }
     }
 }
Example #29
0
 /**
  * 修改php.ini的默认配置
  * @param Yaf\Dispatcher $dispatcher 分发对象
  * @return void
  */
 public function _initRuntime(Dispatcher $dispatcher)
 {
     if ($runtime = Application::app()->getConfig()->get('runtime')) {
         foreach ($runtime->toArray() as $prefix => $suffix) {
             if (is_array($suffix)) {
                 foreach ($suffix as $option => $value) {
                     ini_set(sprintf("%s.%s", $prefix, $option), $value);
                 }
             } else {
                 ini_set($prefix, $suffix);
             }
         }
     }
 }
Example #30
0
 /**
  * 读取相应的配置初始化XHProf
  *
  * @access public
  * @param \Yaf\Dispatcher $dispatcher
  * @return void
  */
 public function _initXHProf(Dispatcher $dispatcher)
 {
     if (isset(Application::app()->getConfig()->application->xhprof)) {
         $xhprof_config = Application::app()->getConfig()->application->xhprof->toArray();
         if (extension_loaded('xhprof') && $xhprof_config && isset($xhprof_config['open']) && $xhprof_config['open']) {
             $default_flags = XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY;
             $ignore_functions = isset($xhprof_config['ignored_functions']) && is_array($xhprof_config['ignored_functions']) ? $xhprof_config['ignored_functions'] : array();
             if (isset($xhprof_config['flags'])) {
                 xhprof_enable($xhprof_config['flags'], $ignore_functions);
             } else {
                 xhprof_enable($default_flags, $ignore_functions);
             }
         }
     }
 }