Skip to content

Instantly share code, notes, and snippets.

@cherifGsoul
Last active July 27, 2016 22:43
Show Gist options
  • Save cherifGsoul/3019ab0a030593b6f21535f93206aa93 to your computer and use it in GitHub Desktop.
Save cherifGsoul/3019ab0a030593b6f21535f93206aa93 to your computer and use it in GitHub Desktop.
Proof of concept and example how to implement facades for yii2 components
<?php
namespace app\components\facades;
/**
* Example how to use the facade class
* uses yii\db\Connection
*/
class Db extends Facade
{
/**
* get the app component name
* @return string
*/
protected static function getComponentName()
{
return 'db';
}
}
<?php
use app\components\facades\Db;
$posts = Db::createCommand('SELECT * FROM posts')->queryAll();
<?php
namespace app\components\facades;
use Yii;
abstract class Facade
{
/**
* get the app component name
* @return string
*/
abstract protected static function getComponentName();
/**
* get the app component instance
* @return Component/Object instance
*/
protected static function provideComponent()
{
$name = static::getComponentName();
return Yii::$app->get($name);
}
/**
* get the app component instance
* @return Component/Object instance
*/
public static function loadComponentInstance()
{
return static::provideComponent();
}
/**
* magic method static calls to the object's method.
*
* @param string $method
* @param array $args
* @return mixed
*
*/
public static function __callStatic($method,$params)
{
$component = static::loadComponentInstance();
return call_user_func_array([$component, $method], $params);
}
}
<?php
namespace app\components\facades;
/**
* Example how to use the facade class
* uses yii\web\View
*/
class View extends Facade
{
/**
* get the app component name
* @return string
*/
protected static function getComponentName()
{
return 'view';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment