getDefault() public static method

public static getDefault ( )
Example #1
1
 public function addComment($data)
 {
     /** @var myModel $this */
     $comment = new Comments();
     $comment->content = $data['content'];
     $comment->commentable_id = $this->id;
     $comment->commentable_type = get_class($this);
     //        $comment->user_id = $this->getDI()->getShared('session')->get('auth')['id'];//获得当前登录对象的id
     $user = \Phalcon\Di::getDefault()->get('auth');
     $comment->user_id = $user->id;
     //获得当前登录对象的id
     //        dd($comment);
     $comment->save();
     /** @var myModel $this */
     if (method_exists($this, 'increaseCount')) {
         $this->increaseCount('commentCount');
     } else {
         $this->save();
         //更新时间
     }
     if (is_a($this, 'Tags')) {
         $meta = $this->getTagmetaOrNew();
         $meta->save();
     }
     return $this;
 }
Example #2
0
 public static function run()
 {
     $di = \Phalcon\Di::getDefault();
     $em = $di->get('em');
     // Clear out any non-daily statistics.
     $em->createQuery('DELETE FROM Entity\\Analytics a WHERE a.type != :type')->setParameter('type', 'day')->execute();
     // Pull statistics in from influx.
     $influx = $di->get('influx');
     $daily_stats = $influx->setDatabase('pvlive_stations')->query('SELECT * FROM /1d.*/ WHERE time > now() - 14d', 's');
     $new_records = array();
     $earliest_timestamp = time();
     foreach ($daily_stats as $stat_series => $stat_rows) {
         $series_split = explode('.', $stat_series);
         $station_id = $series_split[1] == 'all' ? NULL : $series_split[2];
         foreach ($stat_rows as $stat_row) {
             if ($stat_row['time'] < $earliest_timestamp) {
                 $earliest_timestamp = $stat_row['time'];
             }
             $new_records[] = array('station_id' => $station_id, 'type' => 'day', 'timestamp' => $stat_row['time'], 'number_min' => (int) $stat_row['min'], 'number_max' => (int) $stat_row['max'], 'number_avg' => round($stat_row['value']));
         }
     }
     $em->createQuery('DELETE FROM Entity\\Analytics a WHERE a.timestamp >= :earliest')->setParameter('earliest', $earliest_timestamp)->execute();
     foreach ($new_records as $new_record) {
         $row = new \Entity\Analytics();
         $row->fromArray($new_record);
         $em->persist($row);
     }
     $em->flush();
 }
 /**
  * @return Client
  */
 public function getConnection()
 {
     if (static::$connection === null) {
         static::$connection = Di::getDefault()->getShared('Neo4jClient');
     }
     return static::$connection;
 }
Example #4
0
 public static function getDbName()
 {
     if (!isset(self::$_db)) {
         self::$_db = Di::getDefault()->get('config')->mongodb->database;
     }
     return self::$_db;
 }
 /**
  * 根据学校id归类获取信息
  *
  * @param int $school_id
  *
  * @return mixed
  * @author Hunter.<*****@*****.**>
  */
 public function getStatisticsForSchoolAndGrade($school_id = 0)
 {
     $page = new Page();
     $page_table = $page->getSource();
     $classes = new Classes();
     $classes_table = $classes->getSource();
     $eva_task_log = new EvaTaskLog();
     $eva_task_log_table = $eva_task_log->getSource();
     $sql_query = "select c.grade_id,count(DISTINCT p.id) as countP, 'reading' as type from {$page_table} as p\nleft join (\nSELECT grade_id,GROUP_CONCAT(id) as id_concat FROM {$classes_table}\nwhere school_id=:school_id\ngroup by grade_id\n) c on FIND_IN_SET(p.classes_id,c.id_concat)\nwhere is_finished=0\ngroup by c.grade_id\n\nunion all\n\nselect c.grade_id,count(DISTINCT p.id) as countP, 'reading_finished' as type from {$page_table} as p\nleft join (\nSELECT grade_id,GROUP_CONCAT(id) as id_concat FROM {$classes_table}\nwhere school_id=:school_id\ngroup by grade_id\n) c on FIND_IN_SET(p.classes_id,c.id_concat)\nwhere is_finished=1\ngroup by c.grade_id\n\nunion all\n\nselect c.grade_id,count(DISTINCT p.id) as countP, 'eva_task' as type from {$eva_task_log_table} as p\nleft join (\nSELECT grade_id,GROUP_CONCAT(id) as id_concat FROM {$classes_table}\nwhere school_id=:school_id\ngroup by grade_id\n) c on FIND_IN_SET(p.classes_id,c.id_concat)\ngroup by c.grade_id";
     try {
         if (DEBUG) {
             $logger = Di::getDefault()->getLogger();
             $logger->log($sql_query, \Phalcon\Logger::DEBUG);
         }
         $stmt = $this->di->getDefault()->get('db')->prepare($sql_query);
         $stmt->bindParam(':school_id', $school_id, \PDO::PARAM_INT);
         $stmt->execute();
         $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         return $result;
     } catch (\PDOException $e) {
         if (DEBUG) {
             die($e->getMessage());
         } else {
             $this->di->get('logger_error')->log('PDOException: ' . $e->getMessage(), \Phalcon\Logger::ERROR);
             $this->di->get('dispatcher')->forward(['module' => 'home', 'controller' => 'error', 'action' => 'show_sql_error']);
         }
     }
 }
Example #6
0
 public function isVotedBy(Users $user = null)
 {
     if (null == $user) {
         $user = \Phalcon\Di::getDefault()->get('auth');
     }
     return Vote::query()->where('voteable_type = :type:', ['type' => get_class($this)])->andWhere('voteable_id = :id:', ['id' => $this->id])->andWhere('user_id = :user:'******'user' => $user->id])->execute()->count() > 0;
 }
Example #7
0
    public function run()
    {
        $log = new Stream('php://stdout');
        /** @var Config $config */
        $config = Di::getDefault()->getShared('config');
        $expireDate = new DateTime('now', new DateTimeZone('UTC'));
        $expireDate->modify('+1 month');
        $baseUrl = rtrim($config->get('site')->url, '/');
        $content = <<<EOL
User-agent: *
Allow: /
Sitemap: {$baseUrl}/sitemap.xml
EOL;
        $adapter = new Local(dirname(dirname(__FILE__)) . '/public');
        $filesystem = new Filesystem($adapter);
        if ($filesystem->has('robots.txt')) {
            $result = $filesystem->update('robots.txt', $content);
        } else {
            $result = $filesystem->write('robots.txt', $content);
        }
        if ($result) {
            $log->info('The robots.txt was successfully updated');
        } else {
            $log->error('Failed to update the robots.txt file');
        }
    }
Example #8
0
 public static function log($type, $message = null, array $context = [])
 {
     static::$logger or static::$logger = Di::getDefault()->getShared('log');
     $context['host'] = static::$hostname;
     $context['request'] = fnGet($_SERVER, 'REQUEST_METHOD') . ' ' . fnGet($_SERVER, 'REQUEST_URI');
     static::$logger->log($type, $message, $context);
 }
Example #9
0
 public function sqlite(UnitTester $I)
 {
     $I->wantToTest("Model validation by using SQLite as RDBMS");
     /** @var \Phalcon\Di\FactoryDefault $di */
     $di = Di::getDefault();
     $connection = $di->getShared('db');
     $di->remove('db');
     $di->setShared('db', function () {
         $connection = new Sqlite(['dbname' => TEST_DB_SQLITE_NAME]);
         /** @var \PDO $pdo */
         $pdo = $connection->getInternalHandler();
         $pdo->sqliteCreateFunction('now', function () {
             return date('Y-m-d H:i:s');
         });
         return $connection;
     });
     Di::setDefault($di);
     $this->success($I);
     $this->presenceOf($I);
     $this->email($I);
     $this->emailWithDot($I);
     $this->exclusionIn($I);
     $this->inclusionIn($I);
     $this->uniqueness1($I);
     $this->uniqueness2($I);
     $this->regex($I);
     $this->tooLong($I);
     $this->tooShort($I);
     $di->remove('db');
     $di->setShared('db', $connection);
 }
Example #10
0
 /**
  * 跟find()类似,包含总数、页数、上一页、下一页等信息
  *
  * @param $parameters
  * @param int $limit
  * @param int $page
  * @return mixed
  */
 public static function list($parameters = null, $page = 1, $limit = 20)
 {
     // static function.
     $di = Di::getDefault();
     //
     if (!is_array($parameters)) {
         $params[] = $parameters;
     } else {
         $params = $parameters;
     }
     $manager = $di->getShared('modelsManager');
     $builder = $manager->createBuilder($params);
     $builder->from(get_called_class());
     if (isset($params['limit'])) {
         $limit = $params['limit'];
     }
     $params = ["builder" => $builder, "limit" => $limit, "page" => $page];
     $paginator = $di->get("Phalcon\\Paginator\\Adapter\\QueryBuilder", [$params]);
     $data = $paginator->getPaginate();
     $items = [];
     foreach ($data->items as $item) {
         $items[] = $item->toArray();
     }
     $data = (array) $data;
     $data['items'] = $items;
     return $data;
 }
Example #11
0
 /**
  * Opens a connection to the database, using dependency injection.
  * @see \Phalcon\Queue\Db::diServiceKey
  * @return bool
  */
 public function connect()
 {
     if (!$this->connection) {
         $this->connection = Di::getDefault()->get($this->diServiceKey);
     }
     return true;
 }
 public function __get($propertyName)
 {
     $dependencyInjector = null;
     $service = null;
     $persistent = null;
     $dependencyInjector = $this->_dependencyInjector;
     if (!$dependencyInjector) {
         $dependencyInjector = Di::getDefault();
     }
     if (!$dependencyInjector) {
         throw new Exception("A dependency injection object is required to access the application services");
     }
     /**
      * Fallback to the PHP userland if the cache is not available
      */
     if ($dependencyInjector->has($propertyName)) {
         $service = $dependencyInjector->getShared($propertyName);
         $this->{$propertyName} = $service;
         return $service;
     }
     if ($propertyName == "di") {
         $this->{"di"} = $dependencyInjector;
         return $dependencyInjector;
     }
     /**
      * A notice is shown if the property is not defined and isn't a valid service
      */
     trigger_error("Access to undefined property " . $propertyName);
     return null;
 }
Example #13
0
 /**
  * Class constructor.
  *
  * @param  array $options
  * @param  DbConnection  $db
  * @throws ValidationException
  */
 public function __construct(array $options = [], DbConnection $db = null)
 {
     parent::__construct($options);
     if (!$db) {
         // try to get db instance from default Dependency Injection
         $di = Di::getDefault();
         if ($di instanceof DiInterface && $di->has('db')) {
             $db = $di->get('db');
         }
     }
     if (!$db instanceof DbConnection) {
         throw new ValidationException('Validator Uniqueness require connection to database');
     }
     if (!$this->hasOption('table')) {
         throw new ValidationException('Validator require table option to be set');
     }
     if (!$this->hasOption('column')) {
         throw new ValidationException('Validator require column option to be set');
     }
     if ($this->hasOption('exclude')) {
         $exclude = $this->getOption('exclude');
         if (!isset($exclude['column']) || empty($exclude['column'])) {
             throw new ValidationException('Validator with "exclude" option require column option to be set');
         }
         if (!isset($exclude['value']) || empty($exclude['value'])) {
             throw new ValidationException('Validator with "exclude" option require value option to be set');
         }
     }
     $this->db = $db;
 }
Example #14
0
 public function getWatchList()
 {
     if (null == $this->watchList) {
         $user = \Phalcon\Di::getDefault()->get('auth');
         $this->watchList = Watchlist::findOrCreateNew($this, $user);
     }
     return $this->watchList;
 }
Example #15
0
 function __construct($id = null)
 {
     $this->redis = Di::getDefault()->getShared('redis');
     //这里是否会出现一大堆connection呢?怎么能够查询出来呢?
     if (method_exists($this, 'init') and null != $id) {
         $this->init($id);
     }
 }
Example #16
0
 public function getMyWatchListMovies()
 {
     if ([] == $this->watchListMovies) {
         $auth = \Phalcon\Di::getDefault()->get('auth');
         $this->watchListMovies = Watchlist::query()->leftJoin('Movies', 'Movies.id = Watchlist.movie_id')->leftJoin('Episodes', 'Episodes.id = Watchlist.currentEpisode_id')->where('Watchlist.user_id = :user:'******'user' => $auth->id])->andWhere('Watchlist.status != "done" ')->orderBy('Watchlist.updated_at DESC')->columns(['Watchlist.*', 'Movies.*', 'Episodes.*'])->execute();
     }
     return $this->watchListMovies;
 }
Example #17
0
 public function __construct()
 {
     $di = \Phalcon\Di::getDefault();
     $cache_driver = $di['cache_driver'];
     $pool = new \Stash\Pool($cache_driver);
     $pool->setNamespace(\FA\Cache::getSitePrefix('doctrine'));
     $this->_cache = $pool;
 }
 /**
  * construct with supplied standard array
  * break list down into smaller properites
  *
  * @param array $errorList
  */
 public function __construct($errorList)
 {
     $di = Di::getDefault();
     // pull from messageBag if no explicit devMessage is provided
     $this->dev = isset($errorList['dev']) ? $errorList['dev'] : $di->get('messageBag')->getString();
     $this->code = isset($errorList['code']) ? $errorList['code'] : null;
     $this->more = isset($errorList['more']) ? $errorList['more'] : null;
 }
Example #19
0
 /**
  * executed before each test
  */
 protected function _before()
 {
     $this->previousDependencyInjector = Di::getDefault();
     $di = new Di();
     $di->set('modelsManager', new Manager());
     if ($this->previousDependencyInjector instanceof DiInterface) {
         Di::setDefault($di);
     }
 }
Example #20
0
 public function __construct()
 {
     //parent::__construct();
     $di = Di::getDefault();
     $this->setDI($di);
     if (strtolower($this->di->get('request')->getMethod()) === 'head') {
         $this->head = true;
     }
 }
Example #21
0
 /**
  * Fetch analytics from the remote service (i.e. active connections, last update)
  *
  * @return int
  */
 public static function fetch()
 {
     $di = \Phalcon\Di::getDefault();
     $config = $di->get('config');
     $url = $config->apis->pvlnode_local_url;
     // Send standard HTTP GET request.
     $connections_raw = file_get_contents($url);
     return @json_decode($connections_raw, true);
 }
Example #22
0
 /**
  * Return list of all variable definitions.
  *
  * @return mixed
  */
 public static function getDefinitions()
 {
     static $var_definitions;
     if (!$var_definitions) {
         $di = \Phalcon\Di::getDefault();
         $var_definitions = $di['config']->fa->user_variables->toArray();
     }
     return $var_definitions;
 }
 public function setUp()
 {
     parent::setUp();
     // Загрузка дополнительных сервисов, которые могут потребоваться во время тестирования
     $di = Di::getDefault();
     // получаем любые компоненты DI, если у вас есть настройки, не забудьте передать их родителю
     $this->setDi($di);
     $this->_loaded = true;
 }
 public function handle($strUrl = null)
 {
     /**
      * @type \DiCustom $di
      */
     $di = Di::getDefault();
     $oLogger = $di->getFileLogger();
     $oLogger->debug('handle worked in api module for "' . $strUrl . '"');
     parent::handle($strUrl);
 }
Example #25
0
 public function __construct()
 {
     $di = \Phalcon\Di::getDefault();
     $config = $di->get('config');
     $apis_config = $config->apis->toArray();
     if (empty($apis_config) || !isset($apis_config['recaptcha'])) {
         throw new \FA\Exception('Recaptcha is not configured in apis.conf.php!');
     }
     $this->config = $apis_config['recaptcha'];
 }
Example #26
0
 public function getModelPrimaryKey()
 {
     if (!$this->_modelPrimaryKey) {
         /** @var \Phalcon\Mvc\Model\MetaData $modelsMetaData */
         $modelsMetaData = Di::getDefault()->get(Services::MODELS_METADATA);
         $modelClass = $this->getModel();
         $this->_modelPrimaryKey = $modelsMetaData->getIdentityField(new $modelClass());
     }
     return $this->_modelPrimaryKey;
 }
Example #27
0
 protected function success(UnitTester $I)
 {
     /** @var \Phalcon\Di\FactoryDefault $di */
     $di = Di::getDefault();
     /** @var \Phalcon\Db\Adapter\Pdo\Mysql $connection */
     $connection = $di->getShared('db');
     $I->assertTrue($connection->delete('subscriptores'));
     $model = new Subscriptores();
     $I->assertTrue($model->save(['email' => '*****@*****.**', 'created_at' => new RawValue('now()'), 'status' => 'A']));
 }
Example #28
0
 public static function getFileUrl($file_name)
 {
     $di = \Phalcon\Di::getDefault();
     $url = $di['url'];
     if (defined('DF_UPLOAD_URL')) {
         return DF_UPLOAD_URL . '/' . $file_name;
     } else {
         return $url->content($file_name);
     }
 }
 /**
  * process injected model
  *
  * @param BaseModel $model
  * @param SearchHelper $searchHelper
  * @param Entity $entity
  */
 function __construct(BaseModel $model, SearchHelper $searchHelper, Entity $entity)
 {
     $di = Di::getDefault();
     $this->setDI($di);
     // the primary model associated with with entity
     $this->model = $model;
     $this->entity = $entity;
     // a searchHelper, needed anytime we load an entity
     $this->searchHelper = $searchHelper;
 }
Example #30
0
	public static function getFirstLetters()
	{
		$pdo = \Phalcon\Di::getDefault()->getShared('db');
		
		$result = $pdo->query('SELECT DISTINCT LEFT(title, 1) as letter FROM `hashtags` ORDER BY letter');
		
		$letters = $result->fetchAll();
		
		return $letters;
	}