private function invokeModel() { $cfg = \ActiveRecord\Config::instance(); $cfg->set_model_directory($this->registry->appDir . '/models/'); $cfg->set_connections($this->connections); $cfg->set_default_connection($this->defaultConnection); }
public function tearDown() { // Config::instance()->setDateClass($this->original_date_class); if ($this->original_default_connection) { Config::instance()->setDefaultConnection($this->original_default_connection); } }
/** * Retrieve a database connection. * * @param string $connection_string_or_connection_name A database connection string (ex. mysql://user:pass@host[:port]/dbname) * Everything after the protocol:// part is specific to the connection adapter. * OR * A connection name that is set in ActiveRecord\Config * If null it will use the default connection specified by ActiveRecord\Config->set_default_connection * @return Connection * @see parse_connection_url */ public static function instance($connection_string_or_connection_name = null) { $config = Config::instance(); if (strpos($connection_string_or_connection_name, '://') === false) { $connection_string = $connection_string_or_connection_name ? $config->get_connection($connection_string_or_connection_name) : $config->get_default_connection_string(); } else { $connection_string = $connection_string_or_connection_name; } if (!$connection_string) { throw new DatabaseException("Empty connection string"); } $info = static::parse_connection_url($connection_string); $fqclass = static::load_adapter_class($info->protocol); try { $connection = new $fqclass($info); $connection->protocol = $info->protocol; $connection->logging = $config->get_logging(); $connection->logger = $connection->logging ? $config->get_logger() : null; if (isset($info->charset)) { $connection->set_encoding($info->charset); } } catch (PDOException $e) { throw new DatabaseException($e); } return $connection; }
public function __construct() { require_once $_ENV['path']['vendor_path'] . 'php-activerecord/ActiveRecord.php'; $cfg = \ActiveRecord\Config::instance(); //$cfg->set_model_directory('/path/to/your/model_directory'); $cfg->set_connections(['development' => 'mysql://*****:*****@localhost/test']); $cfg->set_default_connection('development'); }
/** * Drops the connection from the connection manager. Does not actually close it since there * is no close method in PDO. * * @param string $name Name of the connection to forget about */ public static function dropConnection($name = null) { $config = Config::instance(); $name = $name ? $name : $config->getDefaultConnection(); if (isset(self::$connections[$name])) { unset(self::$connections[$name]); } }
/** * If $name is null then the default connection will be returned. * * @see Config * @param string $name Optional name of a connection * @return Connection */ public static function get_connection($name = null) { $config = Config::instance(); $name = $name ? $name : $config->get_default_connection(); if (!isset(self::$connections[$name]) || !self::$connections[$name]->connection) { self::$connections[$name] = Connection::instance($config->get_connection($name)); // If we have PHP DebugBar installed then we wrap the connection around it and register it if (is_a(self::$connections[$name]->connection, 'PDO') && class_exists('DebugBar\\DebugBar') && self::$debugBarConnections != null) { self::$connections[$name]->connection = new TraceablePDO(self::$connections[$name]->connection); self::$debugBarConnections->addConnection(self::$connections[$name]->connection, $name . ' #' . (count(self::$debugBarConnections->getConnections()) + 1)); } } return self::$connections[$name]; }
/** * Changes the model's active database connection. * * An instance of the ActiveRecord ConnectionManager class * singleton is used to ensure we don't open wasteful new * connections all over the place. * * The function returns the name of the connection being * replaced. * * @param string $name New connection name * @return string Old connection name * @throws ActiveRecord\DatabaseException on invalid connection name */ public function switch_connection($name) { $cfg = \ActiveRecord\Config::instance(); $valid = $cfg->get_connections(); if (!isset($valid[$name])) { throw new \ActiveRecord\DatabaseException('Conexão especificada inválida'); } // Get the name of the current connection $old = self::$connection; $cm = \ActiveRecord\ConnectionManager::instance(); $conn = $cm::get_connection($name); static::table()->conn = $conn; return $old; }
/** * Initialize AR * * @return void */ private function _initialize(Application $app) { $dbPath = $app['basepath'] . $app['config']['parameters']['db.models.path']; $dbConnectionProduction = $app['config']['parameters']['db.connection.production']; $dbConnectionDevelopment = $app['config']['parameters']['db.connection.development']; $dbConnectionTest = $app['config']['parameters']['db.connection.test']; //----------------------- // Initialize AR $cfg = \ActiveRecord\Config::instance(); $cfg->set_model_directory($dbPath); $cfg->set_connections(array('production' => $dbConnectionProduction, 'development' => $dbConnectionDevelopment, 'test' => $dbConnectionTest)); $cfg->set_date_format("Y-m-d H:i:s"); $cfg->set_default_connection($app['config']['parameters']['environment']); }
public function db_connect($type = 'development') { // PHP-ActiveRecord Database connection $config = \ActiveRecord\Config::instance(); $settings = $this->config; $config->set_model_directory(Application::root_dir() . '/' . $settings['models_path']); $name = $settings['database']['name']; $username = $settings['database']['user']; $password = $settings['database']['password']; $server = $settings['database']['server']; $config->set_connections(array($type => "mysql://{$username}:{$password}@{$server}/{$name}")); // Get models self::load_file('php/models/loadall.php'); }
public function testConnectWithPort() { $config = Config::instance(); $name = $config->getDefaultConnection(); $url = \parse_url($config->getConnection($name)); $conn = $this->conn; $port = $conn::$default_port; $connection_string = "{$url['scheme']}://{$url['user']}"; if (isset($url['pass'])) { $connection_string = "{$connection_string}:{$url['pass']}"; } $connection_string = "{$connection_string}@{$url['host']}:{$port}{$url['path']}"; if ($this->conn->protocol != 'sqlite') { Connection::instance($connection_string); } }
function activerecord_autoload($class_name) { $path = \ActiveRecord\Config::instance()->get_model_directory(); $root = realpath(isset($path) ? $path : '.'); if ($namespaces = ActiveRecord\get_namespaces($class_name)) { $class_name = array_pop($namespaces); $directories = array(); foreach ($namespaces as $directory) { $directories[] = $directory; } $root .= DIRECTORY_SEPARATOR . implode($directories, DIRECTORY_SEPARATOR); } $file = "{$root}/{$class_name}.php"; if (file_exists($file)) { require $file; } }
public function __construct($attributes = array(), $guard_attributes = true, $instantiating_via_find = false, $new_record = true) { $className = (new \ReflectionClass($this))->getShortName(); self::$table_name = strtolower($className); if (self::$connection == null) { $cfg = \ActiveRecord\Config::instance(); self::$dsn = $cfg->get_default_connection_string(); } $pdo = $this->connection()->connection; $this->validationRulesBuilder = new ValidationRulesBuilder(self::$table_name, self::$dsn, $pdo); if (!isset(self::$ruleList[self::$table_name])) { $this->buildRules(); $this->populateRules(); } else { // for code coverage analysis } parent::__construct($attributes, $guard_attributes, $instantiating_via_find, $new_record); }
public static function initialize_activerecord() { Config::instance()->activerecord = \ActiveRecord\Config::instance(); Config::instance()->activerecord->set_model_directory(realpath(HALFMOON_ROOT . "/models/")); /* turn our array of db configs (from the ini file) into php-ar * connection strings */ $dbs = Config::instance()->load_db_config(); $ar_dbs = array(); foreach ($dbs as $henv => $db) { if ($db["socket"] == "") { $host = $db["hostname"] . ":" . $db["port"]; } else { $host = "unix(" . $db["socket"] . ")"; } /* masked strings will be shown in rescue messages */ $ar_dbs[$henv] = new StringMaskedDuringRescue($db["adapter"] . "://" . $db["username"] . ":" . $db["password"] . "@" . $host . "/" . $db["database"] . (empty($db["charset"]) ? "" : "?charset=" . $db["charset"]), $db["adapter"] . "://****/" . $db["database"]); } if (!isset($ar_dbs[HALFMOON_ENV])) { throw new \HalfMoon\HalfMoonException("no database configuration " . "found for \"" . HALFMOON_ENV . "\" environment"); } Config::instance()->activerecord->set_connections($ar_dbs); Config::instance()->activerecord->set_default_connection(HALFMOON_ENV); Config::instance()->initialize_activerecord_logger(); }
/** * Returns the attributes array. * @return array */ public final function to_a() { $date_format = Config::instance()->get_date_format(); foreach ($this->attributes as &$value) { if ($value instanceof \DateTime) { $value = $value->format($date_format); } } return $this->attributes; }
<?php //Propel is a awesome full featured orm that is suitable for mid-sized to large projects //Propel set up is a bit more difficult check out the docs at (http://propelorm.org/) // setup the autoloading /* $serviceContainer = \Propel\Runtime\Propel::getServiceContainer(); $serviceContainer->setAdapterClass('kiss', 'mysql'); $dbcfg = new \Propel\Runtime\Connection\ConnectionManagerSingle(); $dbcfg->setConfiguration(array ( 'dsn' => 'mysql:host=localhost;dbname=propel', 'user' => 'root', 'password' => 'password', )); $serviceContainer->setConnectionManager('kiss', $dbcfg); */ //ActiveRecord is a simple orm that is great for smaller projects. //To start using phpactiveRecord create your db, update your db creds below and add your models to the /models dir. // -- To Use ActiveRecord in your controllers: // $user = models\User::find_by_username('mr user'); // var_dump($user->username); $dbcfg = \ActiveRecord\Config::instance(); $dbcfg->set_model_directory($path . '/models/activerecord'); $dbcfg->set_connections(array('development' => 'mysql://*****:*****@localhost/kiss'));
public function testSetCachetExpire() { Config::instance()->setCache('memcache://localhost', ['expire' => 1]); $this->assertEquals(1, Cache::$options['expire']); }
/** * Configuração do ORM */ public function ActiveRecord() { $cfg = \ActiveRecord\Config::instance(); $cfg->set_model_directory($this->configs->models->directory); $cfg->set_connections(array('development' => 'mysql://' . $this->configs->database->user . ':' . $this->configs->database->password . '@' . $this->configs->database->host . '/' . $this->configs->database->dbname)); }
/** * Converts a string representation of a datetime into a DateTime object. * * @param string $string A datetime in the form accepted by date_create() * @return object The date_class set in Config */ public function string_to_datetime($string) { $date = date_create($string); $errors = \DateTime::getLastErrors(); if ($errors['warning_count'] > 0 || $errors['error_count'] > 0) { return null; } $date_class = Config::instance()->get_date_class(); return $date_class::createFromFormat(static::DATETIME_TRANSLATE_FORMAT, $date->format(static::DATETIME_TRANSLATE_FORMAT), $date->getTimezone()); }
/** * setup database connection and create table in memory * * @throws \ActiveRecord\DatabaseException */ private function __setUpDatabase() { \ActiveRecord\Config::instance()->set_default_connection("test"); $tables = $this->getDatabase()->tables(); foreach ($tables as $table) { if ('sqlite_sequence' == $table) { continue; } $this->getDatabase()->query("DROP TABLE {$table}"); } $sqlcontent = file_get_contents(dirname(__FILE__) . '/acceptance/setup/sqlite.sql'); foreach (explode(";", $sqlcontent) as $sql) { if (trim($sql) == '') { continue; } $this->getDatabase()->query(trim($sql)); } \Yaf\Registry::set('ApplicationDbInit', true); }
/** * Returns the attributes array. * @return array */ public final function to_a() { $date_class = Config::instance()->get_date_class(); foreach ($this->attributes as &$value) { if ($value instanceof $date_class) { $value = $value->format(self::$DATETIME_FORMAT); } } return $this->attributes; }
/** * Constructs an {@link Errors} object. * * @param Model $model The model the error is for * @return Errors */ public function __construct(Model $model) { $this->model = $model; $this->modelName = get_class($model); $cfg = Config::instance(); $error_messages = $cfg->get_error_messages(); if (!empty($error_messages)) { static::$DEFAULT_ERROR_MESSAGES = $error_messages; } }
public function testSetCharset() { $connection_string = Config::instance()->getConnection($this->connection_name); $conn = Connection::instance($connection_string . '?charset=utf8'); $this->assertEquals(';charset=utf8', $conn->dsn_params); }
public function __construct() { $this->request = Request::createFromGlobals(); $this->container = Container::getInstance(); /* Parse params file - Begin */ $params = $this->parseYamlFile(APP_DIR . DS . 'configs' . DS . 'params.yml'); $isDev = $params['environment'] === 'development'; if ($isDev) { Debug::enable(E_STRICT); } date_default_timezone_set($params['timezone']); /* Parse params file - End */ /* Parse routes file - Begin */ $routes = $this->parseYamlFile(APP_DIR . DS . 'configs' . DS . 'routes.yml'); $collection = new RouteCollection(); foreach ($routes as $name => $options) { $parts = explode(':', $options['defaults']['_controller']); $options['defaults'] = array('_controller' => "{$parts[0]}\\Controllers\\{$parts[1]}Controller::{$parts[2]}Action"); $route = new Route($options['path']); $route->setDefaults($options['defaults']); $route->setRequirements(isset($options['requirements']) ? $options['requirements'] : array()); $route->setOptions(isset($options['options']) ? $options['options'] : array()); $route->setHost(isset($options['host']) ? $options['host'] : ''); $route->setSchemes(isset($options['schemes']) ? $options['schemes'] : array()); $route->setMethods(isset($options['methods']) ? $options['methods'] : array()); $route->setCondition(isset($options['condition']) ? $options['condition'] : ''); $collection->add($name, $route); } $this->container->setParameter('routes', $collection); /* Parse routes file - End */ /* Composer ClassLoader - Begin */ $composer_loader = new ClassLoader(); $composer_loader->addPsr4('Application\\Controllers\\', APP_DIR . DS . 'layers' . DS . 'controllers'); $composer_loader->addPsr4('Application\\Models\\', APP_DIR . DS . 'layers' . DS . 'models'); $composer_loader->register(); /* Composer ClassLoader - End */ /* Set error controller - Begin */ $namespace = $isDev ? 'Hideks\\Controller\\' : 'Application\\Controllers\\'; $this->container->setParameter('exception.controller', $namespace . 'ErrorController::exceptionAction'); /* Set error controller - End */ /* Assetic configuration setup - Begin */ $filter_manager = new FilterManager(); $filter_manager->set('css_min', new CssMinFilter()); $filter_manager->set('lessphp', new LessphpFilter()); $filter_manager->set('js_min', new JSMinFilter()); $asset_factory = new AssetFactory(APP_DIR . DS . 'assets' . DS); $asset_factory->setDebug($isDev); $asset_factory->setFilterManager($filter_manager); $asset_factory->addWorker(new CacheBustingWorker()); $this->container->setParameter('assetic.factory', $asset_factory); /* Assetic configuration setup - End */ /* Twig configuration setup - Begin */ $this->container->setParameter('twig.debug', $isDev); $this->container->setParameter('twig.cache', $isDev ? false : APP_DIR . DS . 'cache' . DS . 'twig'); $twig_loader = $this->container->get('twig.loader'); $twig_loader->addPath(APP_DIR . DS . 'layers' . DS . 'views'); /* Twig configuration setup - End */ /* Active Record configuration setup - Begin */ $active_record = \ActiveRecord\Config::instance(); $active_record->set_model_directory(APP_DIR . DS . 'layers' . DS . 'models'); $active_record->set_connections($params['connections']); $active_record->set_default_connection($params['environment']); /* Active Record configuration setup - End */ }
/** * Configuração do ORM */ public function ActiveRecord() { $cfg = \ActiveRecord\Config::instance(); $cfg->set_model_directory($this->configs->models->directory); $cfg->set_connections(['development' => $this->configs->database->driver . '://' . $this->configs->database->user . ':' . $this->configs->database->password . '@' . $this->configs->database->host . '/' . $this->configs->database->dbname . '?charset=' . $this->configs->database->charset]); }
/** * * @param [String] $sql * @return [String] */ public function buildSql($sql) { $config = Config::instance()->get_options(); if (true !== $config['master_slave_enable']) { return $sql; } static $tables = []; $read_oprate = ['select', 'SELECT', 'SHOW', 'show']; //解析出操作符 preg_match("/^\\s*\\(?\\s*(\\w+)\\s/i", $sql, $oprate); //根据配置规则解析出所有表名字 preg_match_all($config['table_preg'], $sql, $output_array); if (in_array($oprate[1], $read_oprate)) { $intersect = array_intersect($tables, $output_array[1]); if (!empty($intersect)) { $sql = "/*" . MYSQLND_MS_MASTER_SWITCH . "*/" . $sql; } } else { $tables = array_unique(array_merge($tables, $output_array[1])); } return $sql; }
public function test_get_model_directory_returns_first_model_directory() { $home = ActiveRecord\Config::instance()->get_model_directory(); $this->config->set_model_directories(array(realpath(__DIR__ . '/models'), realpath(__DIR__ . '/backup-models'))); $this->assert_equals(realpath(__DIR__ . '/models'), $this->config->get_model_directory()); ActiveRecord\Config::instance()->set_model_directory($home); }
public function testSetCharset() { $connection_string = Config::instance()->getConnection($this->connection_name); $conn = Connection::instance($connection_string . '?charset=utf8'); $this->assertEquals("SET NAMES 'utf8'", $conn->last_query); }
static function setup($app) { // Set debug setting $app['debug'] = $app['config']['debug']; // Setup logging $app->register(new \Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => $app['root_path'] . '/app/logs/AppName.log', 'monolog.level' => $app['debug'] ? \Monolog\Logger::DEBUG : \Monolog\Logger::NOTICE, 'monolog.name' => 'AppName')); // Setup sessions $app->register(new SessionServiceProvider()); // Setup PHP Activerecord DB connection if (strncasecmp(PHP_OS, 'WIN', 3) == 0) { // Windows // I couldn't get an absolute path to work on windows. Using relative. $path = 'sqlite://windows(../app/db/db.sqlite)'; } else { // Unix-like $path = 'sqlite://unix(' . $app['root_path'] . '/app/db/db.sqlite)'; } $app['activerecord.cfg'] = \ActiveRecord\Config::instance(); $app['activerecord.cfg']->set_connections(array('prod' => $path)); \ActiveRecord\Config::initialize(function ($cfg) { $cfg->set_default_connection('prod'); }); // Setup symfony php template views $app['view'] = $app->share(function ($app) { $loader = new FilesystemLoader($app['root_path'] . '/app/template/%name%'); $templating = new PhpEngine(new TemplateNameParser(), $loader); // Initialise the slots helper $templating->set(new SlotsHelper()); return $templating; }); // Setup basic app authentication $app->register(new \Silex\Provider\SecurityServiceProvider()); $app->register(new \Silex\Provider\RememberMeServiceProvider()); $app['security.firewalls'] = array('login' => array('pattern' => '^/login$', 'anonymous' => true), 'create_password' => array('pattern' => '^/create_password', 'users' => $app->share(function () use($app) { return new \AppName\Security\UserProvider(); }), 'anonymous' => true), 'main' => array('form' => array('login_path' => '/login', 'check_path' => '/login_check'), 'logout' => array('logout_path' => '/logout'), 'pattern' => '^/', 'users' => $app->share(function () use($app) { return new \AppName\Security\UserProvider(); }), 'remember_me' => array('key' => 'j34krjh23lk4jh23lktc3ktjh', 'name' => 'AppName', 'always_remember_me' => true))); // Conveinience function to get username $app['current_username'] = $app->share(function ($app) { $token = $app['security']->getToken(); // Return username, if available if (null !== $token) { $user = $token->getUser(); return $user->getUsername(); } else { return 'anon'; } }); // Need to boot app here due to security bundle needing to be initialized before being used. // $app->boot(); // Setup custom logging processor. Sets username and IP for every log message // $app['monolog']->pushProcessor(array(new \AppName\Monolog\LogProcessor($app['security']), 'logProcessor')); /** * Accept JSON Requests */ $app->before(function (Request $request) { if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) { $data = json_decode($request->getContent(), true); $request->request->replace(is_array($data) ? $data : array()); } }); /** * Error handler. Return a JSON object with error info */ // $app->error(function(\Exception $e) use ($app){ // // Let this type of exception pass through, it will prompt for authentication. // if($e instanceof \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException) // return; // // Let 404 errors go through // if($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) // return; // $return = array('message' => $e->getMessage()); // $return['class'] = get_class($e); // if($app['debug']){ // $return['trace'] = $e->getTrace(); // $return['file'] = $e->getFile(); // $return['line'] = $e->getLine(); // $return['code'] = $e->getCode(); // } // return $app->json($return, 500); // }, 0); // Debug controllers if ($app['debug']) { $app->get('/make_error/', function (Request $request) use($app) { throw new Exception('Test exception'); return ''; }); } return $app; }
/** * @param \Yaf\Dispatcher $dispatcher */ public function _initDatabase(\Yaf\Dispatcher $dispatcher) { $config = new \Yaf\Config\Ini(APPLICATION_CONFIG_PATH . '/database.ini', \Yaf\ENVIRON); \ActiveRecord\Config::instance()->set_connections($config->database->toArray()); \ActiveRecord\Config::instance()->set_default_connection("master"); }
/** * Converts a string representation of a datetime into a DateTime object. * * @param string $string A datetime in the form accepted by date_create() * @return DateTime */ public function string_to_datetime($string) { $date = date_create($string); $errors = \DateTime::getLastErrors(); if ($errors['warning_count'] > 0 || $errors['error_count'] > 0) { return null; } // return new DateTime($date->format(static::$datetime_format)); //== My change ==// $date_format = Config::instance()->get_date_format(); return new DateTime($date->format($date_format)); //== End my change ==// }