Example #1
0
 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);
 }
Example #2
0
 /**
  * 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;
 }
Example #3
0
 public function runApp()
 {
     $run_info = URLParser\URLParser::getPeices();
     # Include it and call it, really basic
     include APP_PATH . DS . 'controllers' . DS . $run_info['controller'] . '_controller.php';
     $controller_name = ucwords($run_info['controller']) . 'Controller';
     $this->controller = new $controller_name();
     # Load up the database includes if there is one specified
     if (Config::read('DATABASE_CONNECTOR') !== '') {
         include LITEFRAME_PATH . DS . 'lib' . DS . 'php-activerecord' . DS . 'ActiveRecord.php';
         $connections = Config::read('DATABASE_CONNECTIONS');
         $default_connection = Config::read('DATABASE_CONNECTOR');
         $model_path = APP_PATH . DS . 'models';
         # must issue a "use" statement in your closure if passing variables
         \ActiveRecord\Config::initialize(function ($cfg) use($connections, $default_connection, $model_path) {
             $cfg->set_model_directory($model_path);
             $cfg->set_connections($connections);
             # default connection is now production
             $cfg->set_default_connection($default_connection);
         });
     }
     call_user_func_array(array($this->controller, 'init'), array());
     ob_start();
     call_user_func_array(array($this->controller, $run_info['function']), $run_info['args']);
     $content_for_layout = ob_get_clean();
     ob_end_clean();
     $title_for_layout = $this->controller->title;
     # Finally output with a global layout
     if ($this->controller->layout !== '') {
         include APP_PATH . DS . 'layouts' . DS . $this->controller->layout . '.tpl';
     } else {
         include LITEFRAME_PATH . DS . 'layouts' . DS . 'default.tpl';
     }
 }
Example #4
0
 public function tearDown()
 {
     // Config::instance()->setDateClass($this->original_date_class);
     if ($this->original_default_connection) {
         Config::instance()->setDefaultConnection($this->original_default_connection);
     }
 }
 public function testInitializeClosure()
 {
     $test = $this;
     Config::initialize(function ($cfg) use($test) {
         $test->assertNotNull($cfg);
         $test->assertEquals('ActiveRecord\\Config', get_class($cfg));
     });
 }
 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');
 }
Example #7
0
 public function test_initialize_closure()
 {
     $test = $this;
     Config::initialize(function ($cfg) use($test) {
         $test->assert_not_null($cfg);
         $test->assert_equals('ActiveRecord\\Config', get_class($cfg));
     });
 }
 /**
  * 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]);
     }
 }
Example #9
0
 private function connect()
 {
     Config::initialize(function ($cfg) {
         $modelDirectory = APP_PATH . '/Models';
         $configInfo = $this->getConnectType();
         $cfg->set_model_directory($modelDirectory);
         $cfg->set_connections(array('development' => $configInfo));
     });
 }
 public function register(Application $app)
 {
     require_once $app['ar.lib_path'] . '/ActiveRecord.php';
     $app['autoloader']->registerNamespace('ActiveRecord', $app['ar.lib_path'] . '/lib');
     \ActiveRecord\Config::initialize(function ($cfg) use($app) {
         $cfg->set_connections($app['ar.connections']);
         $cfg->set_default_connection($app['ar.default_connection']);
     });
 }
 function register(Application $app)
 {
     $this->app = $app;
     $app['ActiveRecord.init'] = $app->share(function (Application $app) {
         \ActiveRecord\Config::initialize(function ($cfg) use($app) {
             $cfg->set_model_directory($app['ActiveRecord.modelPath']);
             $cfg->set_connections($app['ActiveRecord.connections']);
             $cfg->set_default_connection($app['ActiveRecord.defaultConnection']);
         });
     });
 }
 public static function ensureDatabaseConfigured()
 {
     static $isConnected = false;
     if (!$isConnected) {
         \ActiveRecord\Config::initialize(function ($cfg) {
             $cfg->set_model_directory(SRC_PATH . '/api/Models');
             $cfg->set_connections(array('public' => 'mysql://' . DB_USER . ':' . DB_PASS . '@localhost/languagedepot', 'private' => 'mysql://' . DB_USER . ':' . DB_PASS . '@localhost/languagedepotpvt'));
             $cfg->set_default_connection('public');
         });
     }
 }
Example #13
0
 /**
  * @param null $default
  * @return bool
  */
 public static function instance($default = null)
 {
     if (!static::$instance) {
         $conf = self::config('database');
         Config::initialize(function ($set) use($conf, $default) {
             $set->set_model_directory(ROOT . S . $conf->get('models', 'engine/Models'));
             $set->set_connections($conf->get('connections'), !is_null($default) ? $default : $conf->get('default_connection', 'default'));
         });
         static::$instance = true;
     }
     return static::$instance;
 }
Example #14
0
 public function connect()
 {
     $connections = array();
     foreach (parent::$databases as $name => $db) {
         $connections[$name] = App::dbConn($name);
     }
     ActiveRecord\Config::initialize(function ($cfg) use($connections) {
         $cfg->set_model_directory('models');
         $cfg->set_connections($connections);
         # default connection is first
         $cfg->set_default_connection(key($connections));
     });
 }
Example #15
0
 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');
 }
 /**
  * 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];
 }
Example #17
0
 /**
  * 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;
 }
Example #18
0
 /**
  * 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']);
 }
Example #19
0
 protected function setORM()
 {
     $app = $this;
     \ActiveRecord\Config::initialize(function ($cfg) use($app) {
         $cfg->set_model_directory(ZI . '/models');
         $cfg->set_connections(array_combine(array_keys($app->db), array_map(function ($cfg) {
             if ($cfg['driver'] == 'sqlite') {
                 return $cfg['driver'] . "://" . $cfg['database'];
             } else {
                 return $cfg['driver'] . "://" . $cfg['username'] . ":" . $cfg['password'] . "@" . $cfg['host'] . "/" . $cfg['database'];
             }
         }, $app->db)));
         $cfg->set_default_connection($app->mode);
     });
     $this->conn = \ActiveRecord\ConnectionManager::get_connection($app->mode);
 }
Example #20
0
 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);
     }
 }
Example #21
0
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;
    }
}
Example #22
0
 /**
  * setups db using activerecord
  */
 public static function PRE_init_db()
 {
     # init activerecord configs
     \ActiveRecord\Config::initialize(function ($cfg) {
         # fetching db related configurations
         $dbcfg = \zinux\kernel\application\config::GetConfig("idisqus.db");
         # setting connection string
         $cfg->set_connections(array(\application\dbBootstrap::MODE_TORATAN => "{$dbcfg["type"]}://{$dbcfg["username"]}:{$dbcfg["password"]}@{$dbcfg["host"]}/{$dbcfg["name"]}?charset=utf8"));
         # enable the connection string as to \application\dbBootstrap::MODE_TORATAN
         $cfg->set_default_connection(\application\dbBootstrap::MODE_TORATAN);
     });
     # set default datetime format
     \ActiveRecord\DateTime::$DEFAULT_FORMAT = "iso8601";
     # testing db connection
     \ActiveRecord\Connection::instance();
     # if we reach here we are all OK
 }
 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 function Start()
 {
     $directory = MVC_ROOT_PATH . DIRECTORY_SEPARATOR . 'locale';
     $domain = 'domain';
     $locale = "pt_BR.utf8";
     putenv("LANG=" . $locale);
     //not needed for my tests, but people say it's useful for windows
     setlocale(LC_ALL, $locale);
     bindtextdomain($domain, $directory);
     textdomain($domain);
     bind_textdomain_codeset($domain, 'UTF-8');
     \ActiveRecord\Config::initialize(function ($cfg) {
         $connectionStrings = \System\Configuration\ConfigurationManager::ConnectionStrings();
         $cfg->set_model_directory(MVC_ROOT_PATH . 'Domain');
         $cfg->set_connections(array('Development' => $connectionStrings["Development"], 'Production' => $connectionStrings["Production"]));
         $cfg->set_default_connection('Development');
     });
     \System\Mvc\AreaRegistration::RegisterAllAreas();
     self::RegisterRoutes(\System\Routing\RouteTable::GetRoutes());
 }
Example #25
0
 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();
 }
Example #26
0
<?php

// Load database configuration
require Sea\DIR . '/config/' . App\ENV . '/database.php';
// Initialize ActiveRecord configuration
\ActiveRecord\Config::initialize(function ($cfg) use($db) {
    // Set path to models directory
    $cfg->set_model_directory(Sea\DIR . 'app/models/');
    // Define connections as protocol url
    foreach ($db['connections'] as $connection => $options) {
        $connections[$connection] = $options['type'] . '://' . $options['user'] . ':' . $options['password'] . '@' . $options['server'] . '/' . $options['name'] . '?charset=' . $options['charset'];
    }
    // Set connections
    $cfg->set_connections($connections);
    // Set default connection
    $cfg->set_default_connection($db['default']);
});
Example #27
0
 /**
  * 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());
 }
Example #28
0
 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);
 }
Example #29
0
date_default_timezone_set('America/Bahia');
// Setting constant
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(dirname(__FILE__)));
define('MODELS', ROOT . DS . 'app' . DS . 'models');
define('ROUTES', ROOT . DS . 'app' . DS . 'routes');
define('TEMPLATE_DEFAULT', ROOT . DS . 'app' . DS . 'template' . DS . 'default');
define('LOGS', ROOT . DS . 'logs');
$composer_autoload = ROOT . DS . 'vendor' . DS . 'autoload.php';
if (!file_exists($composer_autoload)) {
    die('Install composer.');
}
require $composer_autoload;
// php-activerecord
\ActiveRecord\Config::initialize(function ($cfg) {
    $cfg->set_model_directory(MODELS);
    $cfg->set_connections(array('development' => 'mysql://*****:*****@localhost/database_name'));
});
// slim-framework
$app = new \Slim\Slim(array('templates.path' => TEMPLATE_DEFAULT));
// Create monolog logger and store logger in container as singleton
// (Singleton resources retrieve the same log resource definition each time)
$app->container->singleton('log', function () {
    $Logger = new \Monolog\Logger('slim-skeleton-full');
    $Logger->pushHandler(new \Monolog\Handler\StreamHandler(LOGS, \Monolog\Logger::DEBUG));
    return $Logger;
});
// Prepare view
$app->view(new \Slim\Views\Twig());
$app->view->parserOptions = array('charset' => 'utf-8', 'cache' => TEMPLATE_DEFAULT . DS . 'cache', 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true);
$app->view->parserExtensions = array(new \Slim\Views\TwigExtension());
// Include routes
Example #30
0
 /**
  * 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);
 }