Yii-using-controllers
Yii-コントローラーの使用
Webアプリケーションのコントローラーは、 yii \ web \ Controller またはその子クラスから拡張する必要があります。 コンソールアプリケーションでは、yii \ console \ Controllerまたはその子クラスから拡張する必要があります。
*controllers* フォルダーにコントローラーの例を作成してみましょう。
ステップ1 *- *Controllers フォルダー内で、次のコードを使用して ExampleController.php というファイルを作成します。
<?php
namespace app\controllers;
use yii\web\Controller;
class ExampleController extends Controller {
public function actionIndex() {
$message = "index action of the ExampleController";
return $this->render("example",[
'message' => $message
]);
}
}
?>
ステップ2 *- *views/example フォルダーにサンプルビューを作成します。 そのフォルダー内で、 example.php というファイルを次のコードで作成します。
<?php
echo $message;
?>
各アプリケーションにはデフォルトのコントローラーがあります。 Webアプリケーションの場合、サイトはコントローラーですが、コンソールアプリケーションの場合はヘルプです。 したがって、 http://localhost:8080/index.php URLが開かれると、サイトコントローラーが要求を処理します。 アプリケーション構成でデフォルトのコントローラーを変更できます。
指定されたコードを考慮してください-
'defaultRoute' => 'main'
ステップ3 *-上記のコードを次の *config/web.php に追加します。
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
//!!! insert a secret key in the following (if it is empty) - this is
//required by cookie validation
'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
//send all mails to a file by default. You have to set
//'useFileTransport' to false and configure a transport
//for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
//changing the default controller
'defaultRoute' => 'example',
'params' => $params,
];
if (YII_ENV_DEV) {
//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 *-Webブラウザーのアドレスバーに *http://localhost:8080/index.php と入力すると、デフォルトのコントローラーがサンプルのコントローラーであることがわかります。
注-コントローラIDには、小文字の英文字、数字、スラッシュ、ハイフン、およびアンダースコアを含める必要があります。
コントローラIDをコントローラクラス名に変換するには、次のことを行う必要があります-
- ハイフンで区切られたすべての単語の最初の文字を大文字に変換します。
- ハイフンを削除します。
- フォワードスラッシュをバックワードスラッシュに置き換えます。
- コントローラーのサフィックスを追加します。
- コントローラーの名前空間を追加します。
例
- ページは app \ controllers \ PageController になります。
- post-articleは app \ controllers \ PostArticleController になります。
- user/post-articleは app \ controllers \ user \ PostArticleController になります。
- userBlogs/post-articleは app \ controllers \ userBlogs \ PostArticleController になります。