Skip to content

Instantly share code, notes, and snippets.

@zmilan
Forked from cherifGsoul/Db.php
Created June 11, 2016 04:58
Show Gist options
  • Save zmilan/d6bef539bddfd02f339090f6cdd4d344 to your computer and use it in GitHub Desktop.
Save zmilan/d6bef539bddfd02f339090f6cdd4d344 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\web\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