I want to try db connection to check is db available. In zend I can place my code in boostrap file and wrap it in try catch.
How to implement this in yii?
Is in yii analog of zend boostrap?
UPD: db is mongo, yii extention for working with db is a directmongosuite
Seems that I find appropriate solution:
Need to prohibit auto connect in config file:
'components' => array(
'edms' => array(
'class' => 'EDMSConnection',
'dbName' => 'homeweb',
'server' => 'mongodb://localhost:27017',
'options' => array('connect' => false)
)
)
all controllers should extend one custom controller (BaseController for example).
Need to write own public function beforeAction method where I can add boostrap code.
class BaseController extends CController
{
public $layout = '//layouts/main';
public $navigationMenu = array();
public $breadcrumbs = array();
public function beforeAction($action)
{
try {
Yii::app()->edmsMongo()->connect();
} catch (Exception $e) {
die('Cannot connect to the database server. Please Try again later.');
}
$isGuest = Yii::app()->user->isGuest;
$this->navigationMenu = $this->_getNavigationMenu($isGuest);
return parent::beforeAction($action);
}
In the beforeAction method need to add return true or execute parent's method.
The bootstrap in yii is pretty much the index.php file under public_html or the yiic.php file (for command line applications).
You will probably have to separate the creating of the application instance and running it (by default it does both on 1 line), so you can do your try/catch between the calls.
Just try to fetch the app component, the mongo plugin will throw an exception if it can't open the connection:
try
{
Yii::app()->mongoDb;
}
...
or Yii::app()->getComponent('mongoDb');
Related
I am working on a project (Zend 1.12.3) which is already completed by the previous developer and now I am working on a task to show some information using another database (Not current Database) on a specific section of the webpage.
I just want to know how do I create a model for the table to another database which is not currently in use. All the configuration of current database is in the application.ini file.
Should I create a custom query in PHTML file to do this (I know this is a bad coding practice) or is there any other way to show the data from both database?
Thank You :)
Finally I found the solution and it works fine because I need only one model file where I have to access data from another database, Following is my model file i.e Ticker.php
- Ticker.php
class Application_Model_DbTable_Ticker extends Zend_Db_Table_Abstract{
protected $_name = "table_name";
public function __construct(){
$adaptor = new Zend_Db_Adapter_Pdo_Mysql(array(
'host' => 'HOST',
'username' => 'DB_USERNAME',
'password' => 'DB_PASSWORD',
'dbname' => 'DB_NAME'
));
$this->_db = $adaptor;
parent::__construct();
}
public function getTopTickers(){
try {
return $this->fetchAll();
} catch(Exception $e) { die($e->getMessage()); };
}
}
I'm using Lumen with an existing PHP application.
There's a conflict in the global namespace. The existing app also have a DB class in the global namespace which is conflicting with the Lumen's DB class.
// in vendor/laravel/lument-framework/src/Appliction.php
public function withFacades()
{
Facade::setFacadeApplication($this);
if (! static::$aliasesRegistered) {
static::$aliasesRegistered = true;
class_alias('Illuminate\Support\Facades\App', 'App');
class_alias('Illuminate\Support\Facades\Auth', 'Auth');
class_alias('Illuminate\Support\Facades\Bus', 'Bus');
class_alias('Illuminate\Support\Facades\DB', 'DB');
...
}
}
If I change class_alias('Illuminate\Support\Facades\DB', 'LumenDB'); solves the problem for me, but I don't want to edit code in the vendor folder.
Is there anyway I can change it programmatically?
Alright. I think I have a workaround for now.
In the bootstrap/app.php uncomment or remove this lines
// $app->withFacades();
and replace with.
class_alias('Illuminate\Support\Facades\App', 'App');
class_alias('Illuminate\Support\Facades\Auth', 'Auth');
class_alias('Illuminate\Support\Facades\Bus', 'Bus');
class_alias('Illuminate\Support\Facades\DB', 'LumenDB');
...
...
class_alias('Illuminate\Support\Facades\Validator', 'Validator');
So we will register the facades manually instead of calling the withFacades() function.
The correct method in newer versions of Laravel/Lumen is to pass an array of "user aliases" as the second argument to the $app->withFacades() method.
$app->withFacades(
true, // $aliases parameter set to true (default)
[
'Illuminate\Support\Facades\DB' => 'LumenDB',
] // array of $userAliases
);
I'm building a toy app in Lithium (PHP framework) based upon the Union of RAD's Framework project. It's all working great in the browser but when running integration tests, routes.php is not loaded, so the routing isn't working.
Here's the code I'm testing:
class StaffController extends \lithium\action\Controller {
public function add() {
$staff = Staff::create();
if (($this->request->data) && $staff->save($this->request->data)) {
return $this->redirect(array('Staff::view', 'args' => array($staff->id)));
}
return compact('staff');
}
My test:
public function testAdd() {
//Router::connect('/{:controller}/{:action}/{:args}');
$request = new Request();
$request->data = array('name' => 'Brand new user');
$controller = new StaffController(array('request' => $request));
/* #var $response \lithium\action\Response */
$response = $controller->add();
$this->assertEqual(302, $response->status['code']);
}
Notice the commented out line - Router::connect('/{:controller}/{:action}/{:args}'); - if I uncomment that, it's all good.
What I'm puzzled about is why, when running in unit tests, app/config/routes.php (where I define my routes) isn't loaded. From what I can determine, app/config/bootstrap/action.php adds a filter to the "run" method of the Dispatcher which loads routes.php.
Of course, it's possible that I am totally missing the point here! I'd appreciate any guidance you can give me!
Lithium has a lithium\action\Dispatcher used for http requests and a lithium\console\Dispatcher for console commands.
I'm assuming you are running tests from the command-line. I'm looking at the "framework" project's app/config/bootstrap/action.php file (here on github).
It is only including the routes.php file for the lithium\action\Dispatcher which is not loaded from the command-line. The app/config/bootstrap/console.php also doesn't include routes.php for the console.
My suggestion is to edit the console.php file and change the filter to look like this:
Dispatcher::applyFilter('run', function($self, $params, $chain) {
Environment::set($params['request']);
foreach (array_reverse(Libraries::get()) as $name => $config) {
if ($name === 'lithium') {
continue;
}
$file = "{$config['path']}/config/routes.php";
file_exists($file) ? call_user_func(function() use ($file) { include $file; }) : null;
}
return $chain->next($self, $params, $chain);
});
dir:
application
-controllers
-models
-views
-mobile_views
How do I auto load templates at mobile_views when I use $this->load->view and view by iphone or other mobile phone?
Check this
You can do it in two way.
Way 1: Its very simple. In the above answer (the link I have given) add following line in the end of MyController function
$this->load->_ci_view_path . = $this->view_type .'/';
You are done. You can simply load view like normal view load.
Way 2:
To autoload a view based on user agent, I think you can implement it using hooks. To implement this hooks you need to follow the following steps
Autoload user agent library in autoload.php
$autoload['libraries'] = array('user_agent');
Enable hooks in config.php
$config['enable_hooks'] = TRUE;
Not implement hooks on post_controller_constructor. Add following codes to hooks.php
$hook['post_controller_constructor'][] = array('class' => 'Loadview',
'function' => 'load',
'filename' => 'loadview.php',
'filepath' => 'hooks'
);
Now create a page named loadview.php under hooks directory having following code
class Loadview
{
public static $MOBILE_PLATFORM = 'mobile';
public static $DEFAULT_PLATFORM = 'default';
public function load(){
$this->CI =& get_instance();
$view_type = $this->CI->agent->is_mobile() ? self::$MOBILE_PLATFORM : self::$DEFAULT_PLATFORM;
$this->CI->load->_ci_view_path = $this->CI->load->_ci_view_path . $view_type .'/';
}
}
You are done now. You can simply load view like normal view load.
to load views from another dir aside from "views", i found this forum topic to be helpful
http://codeigniter.com/forums/viewthread/132960/
function external_view($path, $view, $vars = array(), $return = FALSE)
{
$full_path = $path.$view.'.php';
if (file_exists($full_path))
{
return $this->_ci_load(array('_ci_path' => $full_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
else
{
show_error('Unable to load the requested module template file: '.$view);
}
}
and you can work the rest from the controller.
I do this in my controller:
public function index()
{
if($this->agent->is_mobile())
{
$this->load_mobile();
}
else
{
$this->load_web();
}
}
public function load_mobile()
{
$this->load->view('mobile/home');
}
public function load_web()
{
$this->load->view('web/home');
}
In this way I can add different data to mobile and to web pages.
I also extend the default controller and add some useful extra features:
Enables the usage of master page/templates.
Can add css and javascript files.
Uses the _output method for controlling the controllers output.
Can load relative content with in the form of modules (views)
So I can manage better the different pages.
Bye!!
I just started using a PHP framework, Kohana (V2.3.4) and I am trying to set up a config file for each of my controllers.
I never used a framework before, so obviously Kohana is new to me. I was wondering how I should set up my controllers to read my config file.
For example, I have an article controller and a config file for that controller. I have 3 ways of loading config settings
// config/article.php
$config = array(
'display_limit' => 25, // limit of articles to list
'comment_display_limit' => 20, // limit of comments to list for each article
// other things
);
Should I
A) Load everything into an array of settings
// set a config array
class article_controller extends controller{
public $config = array();
function __construct(){
$this->config = Kohana::config('article');
}
}
B) Load and set each setting as its own property
// set each config as a property
class article_controller extends controller{
public $display_limit;
public $comment_display_limit;
function __construct(){
$config = Kohana::config('article');
foreach ($config as $key => $value){
$this->$key = $value;
}
}
}
C) Load each setting only when needed
// load config settings only when needed
class article_controller extends controller{
function __construct(){}
// list all articles
function show_all(){
$display_limit = Kohana::config('article.display_limit');
}
// list article, with all comments
function show($id = 0){
$comment_display)limit = Kohana::config('article.comment_display_limit');
}
}
Note: Kohana::config() returns an array of items.
Thanks
If you are reading a group of configuration items for a controller, store them in class member ($this->config), if you are reading a single configuration item; read it individually.
I think first method (A) should be fine, it has lesser code and serves the purpose fine.
If you have site wide stuff that you want access to from "anywhere", another way of doing it may be to put something like:
Kohana::$config->attach(new Kohana_Config_File('global'));
in bootstrap.php. Then create global.php in the application/config directory with something like:
return (array ('MyFirstVar' => 'Is One',
'MySecondVar' => 'Is Two'));
And then when you need it from your code:
Kohana::config ('global.MyFirstVar');
But I suppose all of this comes down to where and how you want to use it.