1. 云栖社区>
  2. PHP教程>
  3. 正文

How to create custom Component in Yii2

作者:用户 来源:互联网 时间:2017-12-01 20:10:59

How to create custom Component in Yii2 - 摘要: 本文讲的是How to create custom Component in Yii2, Hi there, Today I would like to write a simple tutorial on creating custom Component in Yii2 and I will show you how to

Hi there, Today I would like to write a simple tutorial on creating custom Component in Yii2 and I will show you how to use created component in your application.

Here is the simple steps, just follow the step at the end you will have your first custom component.

Step1:

Make a folder named “components” in your project root folder.

step2:

Crate a file with desired component name inside components folder and copy past the below code. Example – MyComponent.php

namespaceapp/components;useYii;useyii/base/Component;useyii/base/InvalidConfigException;classMyComponentextendsComponent{publicfunctionwelcome(){ echo"Welcome to MyComponent";}}

Step3:

Add your component inside the config/web.php file

eg:

'components'=>[ 'mycomponent'=>[ 'class'=>'app/components/MyComponent', ], ]

Step4:

You are done!. Now you can use your component method “welcome” inside any of your app controller actions.

eg:controllers/TestController.php

namespaceapp/controllers;useYii;classTestControllerextends/yii/web/Controller{ publicfunctionactionWelcome() { Yii::$app->mycomponent->welcome(); }}

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索,以便于您获取更多的相关知识。