Yii-구성

구성은 새 개체를 만들거나 기존 개체를 초기화하는 데 사용됩니다. 구성에는 일반적으로 클래스 이름과 초기 값 목록이 포함됩니다. 여기에는 이벤트 처리기 및 동작 목록도 포함될 수 있습니다.

다음은 데이터베이스 구성의 예입니다-

<?php
   $config = [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host = localhost;dbname = helloworld', 'username' => 'vladimir', 'password' => '12345', 'charset' => 'utf8', ]; $db = Yii::createObject($config);
?>

그만큼 Yii::createObject() 메소드는 구성 배열을 취하고 구성에 명명 된 클래스를 기반으로 객체를 만듭니다.

구성의 형식-

[
   //a fully qualified class name for the object being created
   'class' => 'ClassName',
   //initial values for the named property
   'propertyName' => 'propertyValue',
   //specifies what handlers should be attached to the object's events
   'on eventName' => $eventHandler,
   //specifies what behaviors should be attached to the object
   'as behaviorName' => $behaviorConfig,
]

기본 애플리케이션 템플릿의 구성 파일은 가장 복잡한 것 중 하나입니다.

<?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'], ], ], ], 'urlManager' => [ //'showScriptName' => false, //'enablePrettyUrl' => true, //'enableStrictParsing' => true, //'suffix' => '/' ], 'db' => require(__DIR__ . '/db.php'), ], 'modules' => [ 'hello' => [ 'class' => 'app\modules\hello\Hello', ], ], '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;
?>

위의 구성 파일에서는 클래스 이름을 정의하지 않았습니다. 이것은 우리가 이미 정의했기 때문입니다.index.php 파일-

<?php
   //defining global constans
   defined('YII_DEBUG') or define('YII_DEBUG', true);
   defined('YII_ENV') or define('YII_ENV', 'dev');
   //register composer autoloader
   require(__DIR__ . '/../vendor/autoload.php');
   //include yii files
   require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
   //load application config
   $config = require(__DIR__ . '/../config/web.php');
   //create, config, and process request
   (new yii\web\Application($config))->run();
?>

많은 위젯도 다음 코드에 표시된 구성을 사용합니다.

<?php
   NavBar::begin([
      'brandLabel' => 'My Company',
      'brandUrl' => Yii::$app->homeUrl,
      'options' => [
         'class' => 'navbar-inverse navbar-fixed-top',
      ],
   ]);
   echo Nav::widget([
      'options' => ['class' => 'navbar-nav navbar-right'],
      'items' => [
         ['label' => 'Home', 'url' => ['/site/index']],
         ['label' => 'About', 'url' => ['/site/about']],
         ['label' => 'Contact', 'url' => ['/site/contact']],
         Yii::$app->user->isGuest ? ['label' => 'Login', 'url' => ['/site/login']] : [ 'label' => 'Logout (' . Yii::$app->user->identity->username . ')',
            'url' => ['/site/logout'],
            'linkOptions' => ['data-method' => 'post']
         ],
      ],
   ]);
   NavBar::end();
?>

구성이 너무 복잡한 경우 일반적인 방법은 배열을 반환하는 PHP 파일을 만드는 것입니다. 보세요config/console.php 구성 파일-

<?php
   Yii::setAlias('@tests', dirname(__DIR__) . '/tests');

   $params = require(__DIR__ . '/params.php'); $db = require(__DIR__ . '/db.php');

   return [
      'id' => 'basic-console',
      'basePath' => dirname(__DIR__),
      'bootstrap' => ['log', 'gii'],
      'controllerNamespace' => 'app\commands',
      'modules' => [
         'gii' => 'yii\gii\Module',
      ],
      'components' => [
         'cache' => [
            'class' => 'yii\caching\FileCache',
         ],
         'log' => [
            'targets' => [
               [
                  'class' => 'yii\log\FileTarget',
                  'levels' => ['error', 'warning'],
               ],
            ],
         ],
         'db' => $db, ], 'params' => $params,
   ];
?>

기본 구성은 다음을 호출하여 지정할 수 있습니다. Yii::$container->set()방법. 이를 통해 지정된 클래스의 모든 인스턴스에 기본 구성을 적용 할 수 있습니다.Yii::createObject() 방법.

예를 들어, yii\widgets\LinkPager 모든 링크 호출기가 최대 3 개의 버튼을 표시하도록하려면 다음 코드를 사용할 수 있습니다.

\Yii::$container->set('yii\widgets\LinkPager', [
   'maxButtonCount' => 3,
]);