Like i want to create function with name "dt()"
function dt(){
return date('Y-m-d H:i:s');
}
and want to access it like this:-
echo dt(); //retrun current date and time format
Which is better place in Yii2 framework to do that?
Like i want to create function with name "dt()"
function dt(){
return date('Y-m-d H:i:s');
}
and want to access it like this:-
echo dt(); //retrun current date and time format
Which is better place in Yii2 framework to do that?
It's not a good approach, but if you insists on having function instead of static class, you can put the method definition in
bootstrap.php
.Usually what I put in bootstrap.php other than defining alias is configuring compability, e.g in fastcgi there is no
getallheaders
, hence I define it there.You can use it this way: http://www.yiiframework.com/extension/yii2-helpers/
Create a folder
/common/helpers/
, then create a helper class there and add your static methods.Usage
I use "common/components" folder. Here i create a file name "AppBasic.php" which will have functions which are for PHP and also Yii related functions.
some of the functions..
I also do the same for controllers. I extend them by the Backendcontroller and FrontendController . They were extended by MosLakeController [My Name] and it is extended by controller.
So i put all access control thing into frontend and backend controller. I also have functions in MosLakeController.
And i also do the same for models. I extend all the ActiveMdels and ALso Models [ Without DB connection] and when theyhave any error afterValidate then i insert data in Database about the error trace with Yii::error() or Yii::info() or Yii::warning().
I do many things to make coding easy and fun and keep learning new things..!!!
For yii2, First Make a folder named
"components"
in your project root folder.Then write your custom component inside components folder .i.e
MyComponent.php
or anything.Now add your component inside the config file.
You are done!. Now you can use your component function "dt" inside any of your controller, model or view..
For example: