1.我们在backend文件下新建components目录作为自定义组件的文件
2.然后再文件夹下新建Sms.php文件,文件中的代码为
<?php
namespace backend\components;
use yii\base\Component;
class Sms extends Component {
public function send($tel) {
echo '给'.$tel.'成功发送了短信';
}
}
3.配置文件中配置
'sms123' => [
'class' => 'backend\components\Sms'
]
具体的代码如下,不用复制全部的代码,复制配置,放到自己的配置文件中,我们这里是配置在文件main-local.php中
<?php
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'BbrwMnBSkmMSoFKXSxr9a8DKal4jHaug',
],
'view' => [
// 'theme' => [
// // 'basePath' => '@backend/web/duanwu',
// 'pathMap' => [
// '@backend/template' => [
// '@backend/template/chunjie',
// '@backend/template/duanwu'
// ]
// ]
// ],
// 'defaultExtension' => 'html'
],
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@backend/messages',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
],
// 'errorHandler' => [
// 'errorAction' => 'test/index17'
// ]
'sms123' => [
'class' => 'backend\components\Sms'
]
],
// 'controllerNamespace' => 'backend\control',
'defaultRoute' => 'test',
'viewPath' => '@backend/template',
// 'layoutPath' => '@backend/template/public'
// 'layout' => false
// 'layout' => 'common'
'language' => 'zh-CN',
'modules' => [
'shop' => [
'class' => 'backend\modules\shop\Module',
]
]
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
4.使用自定义组件
咋控制器中使用自定义组件
public function actionIndex18() {
echo "<pre>";
// print_r(Yii::$app->view);
// print_r(Yii::$app->get('view'));
// print_r(Yii::$app->getView());
// print_r(Yii::$app->get('db'));
Yii::$app->sms123->send('13900000000');
}