1、在app\components下新建MyComponent.PHP
namespace app\components; use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException; class MyComponent extends Component
{
public function welcome()
{
echo "Hello..Welcome to MyComponent";
} }
2、在config/web.php加入你的components
'components' => [ 'mycomponent' => [ 'class' => 'app\components\MyComponent', ],
]
3、在controllers/TestController.php中用你的components
namespace app\controllers;
use Yii; class TestController extends \yii\web\Controller
{
public function actionWelcome()
{
Yii::$app->mycomponent->welcome();
} }
原文地址:http://blog.csdn.net/xiaoyangxiaodong/article/details/45078303