Facades support for Yii 2 application components & classes like Laravel
Run composer require abahrami13/yii2-facades
command.
Add abahrami13\facades\RegisterFacadeAutoloader
to the bootstrap
array in the configuration file (config/web.php
in the basic template).
To use component facade, just import a class started with facades\
followed by the component id. For example for using facade of request component just import facades\Request
:
use facades\Request;
To use facade for other classes, just add facades\
to the start of the class namespace.
For example, for using facade for the app\models\LoginForm
class, just import facades\app\models\LoginForm
class
Just call the desired method statically & enjoy :)
Request::get('foo')
is equal to Yii::$app->request->get('foo')
LoginForm::rules()
is equal to
$loginForm = new LoginForm();
$loginForm->rules()
$random = Yii::$app->security->generateRandomString(128);
import: use facades\Security;
$random = Security::generateRandomString(128);
Yii::$app->session->addFlash('success', 'Wow, Yii is great');
import: use facades\Session;
Session::addFlash('success', 'Wow, Yii is great');
Yii::$app->db->createCommand('SELECT * FROM user')->queryAll();
import: use facades\Db;
Db::createCommand('SELECT * FROM user')->queryAll();
Yii::$app->formatter->asCurrency(123456.78, 'USD');
import: use facades\Formatter;
Formatter::asCurrency(123456.78, 'USD');
import: use app\classes\Greeting;
$obj = new Greeting();
$obj->sayHello('Mr. Mahan');
import: use facades\app\classes\Greeting;
Greeting::sayHello('Mr. Mahan');
import: use app\models\Post;
$post = new Post();
$titleLabel = $post->getAttributeLabel('title');
import: use facades\app\models\Post;
$titleLabel = Post::getAttributeLabel('title');
- All components that are defined in the components array of config file, are supported.
- All Classes (including models, Yii classes, your custom classes & ...) are supported