I created a is_home_page()
function to detect if a user is on the homepage or not, but i'm not sure where i should put it so i can be used on all views and themes?
function is_home_page() {
$app = Yii::app();
return $app->controller->route == $app->defaultController;
}
Applications are objects that govern the overall structure and lifecycle of Yii application systems. Each Yii application system contains a single application object which is created in the entry script and is globally accessible through the expression \Yii::$app .
Open a console terminal, execute the init command and select dev as environment. If you automate it with a script you can execute init in non-interactive mode. Create a new database and adjust the components['db'] configuration in /path/to/yii-application/common/config/main-local. php accordingly.
The yii\base\Controller::init() method is called after the controller is created and configured. The controller creates an action object based on the requested action ID: If the action ID is not specified, the default action ID will be used.
A namespace refers to a logical grouping of some class names so that they can be differentiated from other class names even if their names are the same. Do not confuse path alias with namespace. A path alias is merely a convenient way of naming a file or directory.
create a file a MyClass.php inside components
You can write the static functions inside like
public static function is_home_page() {
$app = Yii::app();
return $app->controller->route == $app->defaultController;
}
which can be accessed from any where like controller, Model or View as below
MyClass::is_home_page();
hope this will help you to write any number of functions globally and access them from anywhere
make a file helpers.php and put it inside components folder
protected
|-components
|-helpers.php
And add this line in the top of your config main.php file
require_once( dirname(__FILE__) . '/../components/helpers.php');
and inside that helpers.php write your function
<?php
function is_home_page() {
$app = Yii::app();
return $app->controller->route == $app->defaultController;
}
?>
Now this function is accessible in whole application directly call is_home_page() any where and it will return your value.
You may create class Globals
with all helpers method. For example:
class Globals{
public function is_home_page() {
$app = Yii::app();
return $app->controller->route == $app->defaultController;
}
}
than in main.php
section components
set:
'globals' => array(
'class' => 'alias.to.location.Globals'
)
than in code you may use this Yii::app()->globals->is_home_page()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With