public function init() { Sky::getLogger()->autoDump = true; Sky::getLogger()->autoFlush = 1; $this->levels = 'info,profile'; parent::init(); }
/** * 执行动作 * @param array $args 命令行参数 * @return integer 非0的应用退出码 */ public function run($args) { $runner = $this->getCommandRunner(); $commands = $runner->commands; if (isset($args[0])) { $name = strtolower($args[0]); } if (!isset($args[0]) || !isset($commands[$name])) { if (!empty($commands)) { echo "Sky command runner (based on Sky v" . Sky::getVersion() . ")\n"; echo "Usage: " . $runner->getScriptName() . " <command-name> [parameters...]\n"; echo "\nThe following commands are available:\n"; $commandNames = array_keys($commands); sort($commandNames); echo ' - ' . implode("\n - ", $commandNames); echo "\n\nTo see individual command help, use the following:\n"; echo " " . $runner->getScriptName() . " help <command-name>\n"; } else { echo "No available commands.\n"; echo "Please define them under the following directory:\n"; echo "\t" . Sky::$app->getCommandPath() . "\n"; } } else { echo $runner->createCommand($name)->getHelp(); } return 1; }
/** * 生成由provider定义的WSDL * @return string 生成的WSDL字符串 */ public function generateWsdl() { $providerClass = is_object($this->provider) ? get_class($this->provider) : \Sky\Sky::import($this->provider, true); $generator = \Sky\Sky::createComponent($this->generatorConfig); $wsdl = $generator->generateWsdl($providerClass, $this->namespace, $this->encoding); return $wsdl; }
/** * Collects and processes log messages from a logger. * This method is an event handler to the {@link \Sky\base\Application::onEndRequest} event. * @param \Sky\base\Event $event 事件参数 */ public function processLogs($event) { $logger = \Sky\Sky::getLogger(); foreach ($this->_routes as $route) { if ($route->enabled) { $route->collectLogs($logger, true); } } }
/** * 开始会话 */ public function open() { if (!$this->_opened) { $this->sessionStart(); if ($this->_sessionId == '') { $this->_opened = false; Sky::log('Failed to start session.', Logger::LEVEL_WARNING, __METHOD__); } else { $this->_opened = true; } } }
/** * 创建一个验证器对象 * @param string $type 验证器的类型。可以使内置验证器的名字或自定义验证器的类名。 * @param \Sky\base\Model $object 要被验证的数据对象。 * @param array|string $attributes 要被验证的属性列表。 * 既可以是包含属性名的数组,也可以是用逗号分隔的属性名。 * @param array $params 要被赋给验证器类的初始属性值。 * @return Validator 验证器类对象 */ public static function createValidator($type, $object, $attributes, $params = array()) { if (is_string($attributes)) { $attributes = preg_split('/[\\s,]+/', $attributes, -1, PREG_SPLIT_NO_EMPTY); } $params['attributes'] = $attributes; if (method_exists($object, $type)) { // 基于方法的验证器。 $params['class'] = __NAMESPACE__ . '\\InlineValidator'; $params['method'] = $type; } else { if (isset(static::$builtInValidators[$type])) { $type = static::$builtInValidators[$type]; } $params['class'] = $type; } $obj = Sky::createComponent($params); $obj->init(); return $obj; }
/** * @param \Sky\base\Controller $controller * @param \Sky\base\Action $action * @param array $filters */ public static function create($controller, $action, $filters) { $chain = new self($controller, $action); $actionID = $action->getId(); foreach ($filters as $filter) { if (is_string($filter)) { if (($pos = strpos($filter, '+')) !== false || ($pos = strpos($filter, '-')) !== false) { $matched = preg_match("/\\b{$actionID}\\b/i", substr($filter, $pos + 1)) > 0; if (($filter[$pos] === '+') === $matched) { $filter = InlineFilter::create($controller, trim(substr($filter, 0, $pos))); } } else { $filter = InlineFilter::create($controller, $filter); } } elseif (is_array($filter)) { if (!isset($filter[0])) { throw new \Exception('The first element in a filter configuration must be the filter class.'); } $filterClass = $filter[0]; unset($filter[0]); if (($pos = strpos($filterClass, '+')) !== false || ($pos = strpos($filterClass, '-')) !== false) { $matched = preg_match("/\\b{$actionID}\\b/i", substr($filterClass, $pos + 1)) > 0; if (($filterClass[$pos] === '+') === $matched) { $filterClass = trim(substr($filterClass, 0, $pos)); } else { continue; } } $filter['class'] = $filterClass; $filter = Sky::createComponent($filter); } if ($filter instanceof Filter) { $filter->init(); $chain->_chainList[] = $filter; // $chain->add($filter); } else { throw new \Exception('FilterChain can only take instance of Filter.'); } } return $chain; }
/** * 开始会话 */ public function open() { // this is available in PHP 5.4.0+ // if (function_exists('session_status')) { // if (session_status() == PHP_SESSION_ACTIVE) { // $this->_opened = true; // return; // } // } if (!$this->_opened) { if ($this->getUseCustomStorage()) { @session_set_save_handler(array($this, 'openSession'), array($this, 'closeSession'), array($this, 'readSession'), array($this, 'writeSession'), array($this, 'destroySession'), array($this, 'gcSession')); } @session_start(); if (session_id() == '') { $this->_opened = false; $error = error_get_last(); $message = isset($error['message']) ? $error['message'] : 'Failed to start session.'; Sky::log($message, Logger::LEVEL_WARNING, __METHOD__); } else { $this->_opened = true; } } }
private function _throwQueryException($errorInfo = null) { if (SKY_DEBUG) { \Sky\Sky::endProfile($this->setText($this), 'system.db'); } throw new \Exception(isset($errorInfo[2]) ? $errorInfo[2] : 'NULL'); }
/** * 返回服务器软件版本信息 * 如果应用部署在生产模式,将返回空字符 * @return string */ protected function getVersionInfo() { if (SKY_DEBUG) { $version = '<a href="http://www.skyworth.com/">SKY Framework</a>/' . \Sky\Sky::getVersion(); if (isset($_SERVER['SERVER_SOFTWARE'])) { $version = $_SERVER['SERVER_SOFTWARE'] . ' ' . $version; } } else { $version = ''; } return $version; }
/** * 从缓存中删除指定键名对应的值 * 这是在父类中定义的方法的具体实现。 * @param string $key 要删除值的键名 * @return boolean 是否删除期间没有发生错误 */ protected function deleteValue($key) { Sky::trace('Memcache delete:' . $key, 'memcache'); return $this->_cache->delete($key, 0); }
/** * 准备要发送的响应。 * @throws \Exception 如果格式不支持的话 */ protected function prepare() { if ($this->data === null) { return; } if (isset($this->formatters[$this->format])) { } else { switch ($this->format) { case self::FORMAT_HTML: $this->setHeader('Content-Type', 'text/html; charset=' . $this->charset); $this->content = $this->data; break; case self::FORMAT_RAW: $this->content = $this->data; break; case self::FORMAT_JSON: $this->setHeader('Content-Type', 'application/json'); $this->content = JSON::encode($this->data); break; case self::FORMAT_JSONP: $this->setHeader('Content-Type', 'text/javascript; charset=' . $this->charset); // if (is_array($this->data) && isset($this->data['data'], $this->data['callback'])) { // $this->content = sprintf('%s(%s);', $this->data['callback'], JSON::encode($this->data['data'])); // } else { if (isset($this->jsonpcallback)) { $this->content = sprintf('%s(%s);', $this->jsonpcallback, JSON::encode($this->data)); } else { $this->content = ''; } break; case self::FORMAT_XML: Sky::createComponent(array('class' => 'Sky\\web\\XmlResponse'))->format($this); break; default: throw new \Exception("Unsupported response format: {$this->format}"); } } }
/** * 配置当前模块的子模块。 * * 调用该方法来声明子模块并用它们的初始属性值配置它们。 * 参数应该是一个包含模块配置的数组。数组的每一个元素代表了一个模块。 * 它既可以是一个代表模块id的字符串,也可以是一个包含模块配置的数组。 * * 例如,下面的数组声明了两个模块: * <pre> * array( * 'admin', //一个单独的模块 ID * 'payment'=>array( //包含配置的数组 * 'server'=>'paymentserver.com', * ), * ) * </pre> * * 你也可以通过配置'enabled'属性来启用或禁用一个模块。 * * @param array $modules 模块配置。 */ public function setModules($modules) { foreach ($modules as $id => $module) { if (is_int($id)) { $id = $module; $module = array(); } if (!isset($module['class'])) { if (($pos = strrpos($id, '\\')) !== false) { $tid = substr($id, $pos + 1); $module['class'] = $id . '\\' . ucfirst($tid) . 'Module'; // $id=$tid; $id = str_replace('\\', '/', $id); } else { $namespace = $id . '\\' . ucfirst($id) . 'Module'; // Sky::log('SET module path:'.$this->getModulePath()); // Sky::log('get class name:'.get_class($this).'***** namespace :'.$namespace); Sky::setPathofNamespace($namespace, $this->getModulePath() . DIRECTORY_SEPARATOR . $id); // Sky::setPathofNamespace($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id); $module['class'] = $namespace; } } if (isset($this->_moduleConfig[$id])) { $this->_moduleConfig[$id] = self::mergeArray($this->_moduleConfig[$id], $module); } else { $this->_moduleConfig[$id] = $module; } } }
/** * * @param mixed $obj any type of variable to profile memory * @param string $msg message to be logged * @param string $category category of the message (e.g. 'system.web'). It is case-insensitive. */ public static function logMemory($obj, $msg = '', $category = 'application') { if (is_string($obj)) { $memory = \Sky\Sky::getLogger()->getMemoryUsage(); $msg = $obj; } else { $memory = strlen(serialize($obj)); } $type = gettype($obj); \Sky\Sky::log("[{$memory}][{$type}] {$msg}", 'memory', $category); }
/** * 处理队列中的消息 * 该方法会先从队列中取出消息,然后放到{@link $_msgArray}中。 * 当满足读取消息超时或消息间隔超时或收到{@link $maxExecCount} * 个消息后,会调用{@link processMsg()}方法。 * @return boolean */ public function consume() { echo "begin consume message...\n"; $pid = getmypid(); while (!$this->_isFinished) { try { $this->_beginTime = time(); $this->_rabbit->queue->consume(array($this, 'myCallback'), 'update' . $pid); } catch (\Exception $e) { if (!$this->_rabbit->isConnected()) { echo "connection timeout\n"; echo $e->getMessage(); return false; } else { echo "it has been too long since previous message.begin process..\n"; } } try { $this->cancelQueue('update' . $pid); $ret = $this->processMsg($this->_msgArray); echo "process " . count($this->_msgArray) . " msg over.\n"; if (SKY_DEBUG && $this->_counter > 0) { $avgTime = sprintf('%01.2f', $this->_totalTime / $this->_counter); // $avgTime=$this->_totalTime/$this->_counter; Sky::log("msg:{$this->_counter} avg queue time:{$avgTime} ms"); } if ($ret === FALSE) { $this->_msgArray = array(); return; } } catch (\Exception $e) { echo $e->getMessage(); $this->_msgArray = array(); return false; } $this->_msgArray = array(); $this->_counter = 0; $this->_totalTime = 0; } }
/** * 在应用程序处理请求之后发起 * @param Event $event 事件参数 */ public function onEndRequest($event) { if (!$this->_ended) { $this->_ended = true; \Sky\Sky::endXProfile('jym'); $this->raiseEvent('onEndRequest', $event); } }
/** * @param string $name 命令名 (大小写敏感) * @return ConsoleCommand 命令对象. 如果名字非法的话返回null. */ public function createCommand($name) { $name = strtolower($name); $command = null; if (isset($this->commands[$name])) { $command = $this->commands[$name]; } else { $commands = array_change_key_case($this->commands); if (isset($commands[$name])) { $command = $commands[$name]; } } // echo $command; if ($command !== null) { if (is_string($command)) { if (strpos($command, '/') !== false) { $classPathName = substr($command, strpos($command, Sky::$app->name), -4); // $classPathName=substr($classPathName, strpos($classPathName, '/')+1); $className = str_replace('/', '\\', $classPathName); // echo $className; if (!class_exists($className, false)) { require_once $command; } } else { throw new \Exception('command ' . $command . ' must be a filepath'); } return new $className($name, $this); } else { // an array configuration return Sky::createComponent($command, $name, $this); } } elseif ($name === 'help') { return new HelpCommand('help', $this); } else { return null; } }
<?php use Sky\Sky; defined('STDIN') or define('STDIN', fopen('php://stdin', 'r')); // defined('SKY_DEBUG') or define('SKY_DEBUG',true); require_once __DIR__ . '/sky.php'; if (isset($config)) { $app = Sky::createConsoleApplication($config); } else { $app = Sky::createConsoleApplication(array('basePath' => __DIR__ . '/cli', 'name' => 'Command App')); } $env = @getenv('SKY_CONSOLE_COMMANDS'); if (!empty($env)) { $app->commandRunner->addCommands($env); } $app->run();