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'; } }
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)); }); }
public function testInitializeClosure() { $test = $this; Config::initialize(function ($cfg) use($test) { $test->assertNotNull($cfg); $test->assertEquals('ActiveRecord\\Config', get_class($cfg)); }); }
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']); }); }
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)); }); }
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'); }); } }
/** * @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; }
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)); }); }
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); }
/** * 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 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()); }
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; }
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
<?php namespace config; use ActiveRecord\Config; $connections = (require __DIR__ . '/db.php'); Config::initialize(function ($cfg) use($connections) { $cfg->set_model_directory(__DIR__ . '/../models'); $cfg->set_connections($connections); });
/** * setup_db_connection * * Setup our DB/ORM and pass it our configuration * * @access private * @return void */ private function setup_db_connection() { // Check to see if ActiveRecord exists... the app/developer might not want to use it if (class_exists('\\ActiveRecord\\Config', true)) { // Set to false to not try and autoload the class \ActiveRecord\Config::initialize(function ($cfg) { // Set the directory of our data models $cfg->set_model_directory($this->config['database']['model_directory']); // Set our connection configuration $cfg->set_connections($this->config['database']['connections']); // Set our default connection $cfg->set_default_connection($this->config['database']['default_connection']); }); } }
if (Config::getPlugins('css') == 'lessCSS') { $lessFile = glob('public/less/*.less'); if (sizeof($lessFile) > 0) { $less = new lessc(); foreach ($lessFile as $value) { $filenames = explode('/', $value); $filename = $filenames[2]; $less->checkedCompile($value, strstr($value, '/', true) . '/css/' . substr($filename, 0, strpos($filename, '.')) . '.css'); } } } //Call caches header if (Config::getConfig(Config::$cache) == 'true') { $router->headerCache(); } AR_Config::initialize(function ($cfg) { $cfg->set_model_directory('app/models'); $cfg->set_connections(Config::getDatabases()); $cfg->set_default_connection(Config::getConfig(Config::$default_connection)); }); //Call controller $router->route(); //Call caches footer if (Config::getConfig(Config::$cache) == 'true') { $router->footerCache(); } //Stop timer $time_end = microtime(true); $time = $time_end - $time_start; //Comment below to hide timer //echo 'Web executed in '.$time.' seconds';
<?php require_once Bundle::path('activerecord') . 'ActiveRecord.php'; Event::listen('laravel.started: activerecord', function () { $connections = Config::get('database.connections'); $default = Config::get('database.default'); $prepared = array(); // Prepare database connections for ActiveRecord foreach ($connections as $k => $conn) { if ($k == 'sqlite') { $prepared[$k] = $conn['driver'] . '://' . $conn['database']; } else { $prepared[$k] = $conn['driver'] . '://' . $conn['username'] . ':' . $conn['password'] . '@' . $conn['host'] . '/' . $conn['database']; } if (in_array($k, array('mysql', 'pgsql'))) { $prepared[$k] .= ';charset=' . $conn['charset']; } } // Initialize the configuration \ActiveRecord\Config::initialize(function ($cfg) use($prepared, $default) { $cfg->set_model_directory(Config::get('activerecord::config.models_dir')); $cfg->set_connections($prepared); $cfg->set_default_connection($default); }); });
<?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']); });
/** * General executor. * * @param array $options * @return string */ public function execute($options = array()) { // Init sessions. session_start(); // Apply application config. Application::$config = new Config(isset($options['config']) && is_array($options['config']) ? $options['config'] : null); // Init debug mode. error_reporting(Application::$config->debug->bool ? E_ALL : 0); // Init Active Record. ActiveRecord\Config::initialize(function ($cfg) { $cfg->set_connections(Application::$config->connections->value); $cfg->set_default_connection(Application::$config->connection->string); if (!Application::$config->directories->isEmpty() && isset(Application::$config->directories->value['models'])) { $base_dir = isset(Application::$config->directories->value['base']) ? Application::$config->directories->value['base'] : __DIR__; $cfg->set_model_directory(str_replace('{{base}}', $base_dir, Application::$config->directories->value['models'])); } }); // Parse only AJAX requests. if (Application::$config->ajax_only->bool && (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')) { header('HTTP/1.1 500 Internal server error'); $response_obj = ResponseBuilder::create(500, "This API allow only AJAX requests.", $_SERVER['HTTP_ACCEPT']); return $response_obj->render(); } // Parse incoming request info. $request = new Request(); // Parse request method & parameters $request->method = strtoupper(isset($options['method']) ? $options['method'] : $_SERVER['REQUEST_METHOD']); if (isset($options['parameters']) && is_array($options['parameters'])) { $request->parameters = new ParametersList($options['parameters']); } else { if (!isset($options['method'])) { switch ($request->method) { case 'GET': $request->parameters = new ParametersList($_GET); break; case 'POST': $request->parameters = new ParametersList($_POST); break; default: $request->parameters = new ParametersList(); break; } } else { $request->parameters = new ParametersList(); } } // Parse routes settings. if (isset($options['path']) || isset($_SERVER['PATH_INFO'])) { $path = trim(isset($options['path']) ? $options['path'] : $_SERVER['PATH_INFO'], '/'); if (!Application::$config->routes->isEmpty() && is_array(Application::$config->routes->value)) { $routes = Application::$config->routes->value; if (isset($routes['general']) && is_array($routes['general'])) { foreach ($routes['general'] as $key => $route) { $path = preg_replace($key, $route, $path); } } if (isset($routes[strtolower($request->method)]) && is_array($routes[strtolower($request->method)])) { foreach ($routes[strtolower($request->method)] as $key => $route) { $path = preg_replace($key, $route, $path); } } } $path_elements = explode('?', $path); if (count($path_elements) > 0) { $path = $path_elements[0]; if (count($path_elements) > 1) { $path_parameters = explode('&', $path_elements[1]); foreach ($path_parameters as $path_parameter) { $path_parameter_pair = explode('=', $path_parameter); switch (count($path_parameter_pair)) { case 1: $request->parameters->add($path_parameter_pair[0]); break; case 2: $request->parameters->add($path_parameter_pair[0], $path_parameter_pair[1]); break; } } } } $request->url_elements = explode('/', trim($path, '/')); } // Parse incoming data. if (isset($options['json'])) { $request->json = is_object($options['json']) ? $options['json'] : json_decode($options['json']); } else { $request_data = file_get_contents('php://input'); $request->json = json_decode($request_data); } // Route the request. if (!empty($request->url_elements) && !empty($request->url_elements[0])) { $controller_name = ucfirst($request->url_elements[0]); $controller_classname = ($this->__attachController($controller_name) ? $controller_name : 'Sija\\Controllers\\' . $controller_name) . 'Controller'; $controller_parents = class_parents($controller_classname); if (class_exists($controller_classname) && $controller_parents && is_array($controller_parents) && in_array("Sija\\Common\\AbstractController", $controller_parents)) { $controller = new $controller_classname(); $action_name = strtolower($request->method); try { $response_status = 200; $response_data = call_user_func_array(array($controller, $action_name), array($request)); } catch (Exception $e) { $response_status = $e->getCode(); $response_data = $e->getMessage(); } } else { header('HTTP/1.1 500 Internal server error'); $response_status = 500; $response_data = 'Unknown request: ' . $request->url_elements[0]; } } else { header('HTTP/1.1 500 Internal server error'); $response_status = 500; $response_data = 'Unknown request'; } // Return response $response_obj = ResponseBuilder::create($response_status, $response_data, $_SERVER['HTTP_ACCEPT']); return $response_obj->render(); }