yii 2 setup and configuration

31
2021/09/18 22:11 1/31 Yii 2 Setup and Configuration CIRC Wiki - https://circ.cs.southern.edu/wiki/ Yii 2 Setup and Configuration Install the following: 1. Download from: Yii Framework 2. Get Yii2 themes from: Theme Factory 3. Get Bootstrap themes from: BootSwatch 4. Get Composer from: GetComposer The Definitive Guide to Yii 2.0Installing Yii2 Install Composer Install composer (from https://getcomposer.org). Windows: Copy composer.phar to C:\ProgramData\ComposerSetup\bin\ Run: echo @\xampp\php\php.exe “%~dp0composer.phar” %*>composer.bat Add C:\ProgramData\ComposerSetup\bin\ to OS environment variable PATH. Update composer. Make sure all composercomponents are up-to-date: C:\> composer self-update C:\> composer global require "fxp/composer-asset-plugin:^1.4.6" --no- plugins # Upgrade a specific package without touching the rest C:\> composer update yiisoft/yii2 yiisoft/yii2-composer bower- asset/jquery.inputmask Install Auth Token for Composer (requires Authentication to GitHub) To solve issues with API rate limiting on GitHub while using Composer, you need to have GitHub credentials.

Upload: others

Post on 01-Oct-2021

23 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Yii 2 Setup and Configuration

2021/09/18 22:11 1/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

Yii 2 Setup and Configuration

Install the following:

1. Download from: Yii Framework

2. Get Yii2 themes from: Theme Factory

3. Get Bootstrap themes from: BootSwatch

4. Get Composer from: GetComposer

The Definitive Guide to Yii 2.0…

Installing Yii2

Install Composer

Install composer (from https://getcomposer.org).Windows:

Copy composer.phar to C:\ProgramData\ComposerSetup\bin\Run: echo @\xampp\php\php.exe “%~dp0composer.phar” %*>composer.batAdd C:\ProgramData\ComposerSetup\bin\ to OS environment variable PATH.

Update composer. Make sure all composercomponents are up-to-date:

C:\> composer self-updateC:\> composer global require "fxp/composer-asset-plugin:^1.4.6" --no-plugins

# Upgrade a specific package without touching the restC:\> composer update yiisoft/yii2 yiisoft/yii2-composer bower-asset/jquery.inputmask

Install Auth Token for Composer (requires Authentication to GitHub)

To solve issues with API rate limiting on GitHub while using Composer, you need to have GitHubcredentials.

Page 2: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

Login (or signup for an free account) at GitHub.Go to Account > Settings > Personal access tokens (https://github.com/settings/applications) anddelete the previous token generated during the installation of yii2.Create a new token. NOTE: Save it somewhere, because it is not going to be readable afterwards.Eg: Name it yii2 composer with access scope public_repo.Register the token with Composer:

C:\> composer config -g github-oauth.github.com <oauthtoken>

Alternatively: Enter credentials in this file: C:\Users\< username>\AppData\Roaming\Composer\auth.json

{ "http-basic": {}, "github-oauth": { "github.com": "<oauthtoken>"}}

Example:

{ "http-basic": {}, "github-oauth": { "github.com": "8dabf7def512b794607a6642806bd737227c8bc0"}}

Install Yii

Run composer command to install Yii.

Install pre-requisites:

$php composer.phar global require "fxp/composer-asset-plugin:^1.4.2"

Choose one of these to install, either the basic or advanced application template:

$php composer.phar create-project yiisoft/yii2-app-basic basic 2.0.15

$php composer.phar create-project yiisoft/yii2-app-advanced advanced2.0.15

Note that you may be prompted to enter your GitHub username and password during the installationprocess. This is normal. Just enter them and continue. If you have not done so already, get a GitHub authtoken.

Page 3: Yii 2 Setup and Configuration

2021/09/18 22:11 3/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

Upgrade Yii

Run command in Yii root folder (where yii command resides):

$ composer update

Follow upgrade instructions if necessary:https://github.com/yiisoft/yii2/blob/master/framework/UPGRADE.mdTroubleshooting: perform these steps before upgrading:

$ composer self-update // to have the latest composer$ composer global update // to make sure latest fxp is used$ composer clear-cache // to make sure success is not because of cache$ composer global require "fxp/composer-asset-plugin:^1.4.2" --no-plugins$ composer require "yiisoft/yii2:~2.0.15" --update-with-dependencies$ composer update yiisoft/yii2 yiisoft/yii2-composer bower-asset/jquery.inputmask

Edit composer.json as follows. Move extra.asset-installer-paths to config.fxp-asset.installer-paths instead:

"extra": { "yii\\composer\\Installer::postCreateProject": { "setPermission": [ { "runtime": "0777", "web/assets": "0777", "yii": "0755" } ], "generateCookieValidationKey": [ "config/web.php" ] }, // Remove //"asset-installer-paths": { // "npm-asset-library": "vendor/npm", // "bower-asset-library": "vendor/bower" //} } "config": { "process-timeout": 1800, // Add "fxp-asset": { "installer-paths": { "npm-asset-library": "vendor/npm",

Page 4: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

"bower-asset-library": "vendor/bower-asset" } } }

Upgrade codeception component (remove yii2-codeception):

"require-dev": { // Remove //"yiisoft/yii2-codeception": "*", // Add "codeception/base": "^2.2.3", "codeception/codeception": "2.3.*", "codeception/specify": "*", "codeception/verify": "*" }

Rename bower references to bower-asset. In@app\vendor\yiisoft\yii2\base\Application.php:

//...public function setVendorPath($path){ $this->_vendorPath = Yii::getAlias($path); Yii::setAlias('@vendor', $this->_vendorPath); Yii::setAlias('@bower', $this->_vendorPath . DIRECTORY_SEPARATOR . 'bower-asset'); // rename bower to bower-asset Yii::setAlias('@npm', $this->_vendorPath . DIRECTORY_SEPARATOR . 'npm');}

Initial Configuration

Prepare config files to support a 'local' (non-version controlled) copy.

For the advanced app:

Generate the local config files. Run this command at project root: [app]$ init.Find config files in common, frontend, backend, and console.

For the basic app:

db.php would need db-local.phpconsole.php would need console-local.php (optional)params.php would need params-local.php

Page 5: Yii 2 Setup and Configuration

2021/09/18 22:11 5/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

web.php would need web-local.php

The local versions would be empty, but you can add parameters to override the respective settings:

<?phpreturn [];

For basic app only: Edit the following to support local copies. [app]/config/web.php,[app]/config/console.php, and [app]/config/test.php:

//$params = require(__DIR__ . '/params.php');$params = array_merge( require(__DIR__ . '/params.php'), require(__DIR__ . '/params-local.php')); //$db = require(__DIR__ . '/db.php');$db = array_merge( require(__DIR__ . '/db.php'), require(__DIR__ . '/db-local.php'));...$config = [ ... 'components' => [ 'db' => $db, //require(__DIR__ . '/db.php'), ],];

For basic app only: [app]/web/index.php:

...//$config = require(__DIR__ . '/../config/web.php');$config = yii\helpers\ArrayHelper::merge( require(__DIR__ . '/../config/web.php'), require(__DIR__ . '/../config/web-local.php'));...

For basic app only: Required for console and migration commands, edit file [app]/yii to support localcopies:

...//$config = require(__DIR__ . '/config/console.php');$config = yii\helpers\ArrayHelper::merge( require(__DIR__ . '/config/console.php'),

Page 6: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

require(__DIR__ . '/config/console-local.php'));...

Database Config

Edit the following configuration files.

/[app]/config/db.php or /[app]/common/config/db.php

return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=acme_dbname', 'username' => 'acme_dbusername', 'password' => 'acme_dbpassword', 'charset' => 'utf8', 'tablePrefix' => 'main_',];

Character Set

Make sure that the charset property is set to match your database, else your emojis (�) won't workproperly if your database has 'utf8mb4' characters but you only specifiy 'utf8' in the db.php config.

'charset' => 'utf8mb4'

Params Config

/[app]/config/params.php or /[app]/common/config/params.php

return [ 'appId' => 'app_intranet', 'appName' => 'Intranet', 'appNameShort' => 'Intranet', 'companyName' => 'Acme, Inc.', 'companyNameShort' => 'Acme', 'companyAddress' => '123 Main St, Maplewood, VA 12345,United States', 'companyEmail' => '[email protected]', 'companyPhone' => '800-123-ACME', 'companyFax' => '800-123-ACME', 'companyWebsite' => 'http://www.acme.com', 'companyWebsiteSecure' => 'https://secure.acme.com', 'adminEmail' => '[email protected]',

Page 7: Yii 2 Setup and Configuration

2021/09/18 22:11 7/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

'supportEmail' => '[email protected]', 'debugEmail' => '[email protected]', 'urlWebmail' =>'https://outlook.office365.com/owa/?realm=acme.com', 'urlSocialFacebook' => 'https://www.facebook.com/acme', 'urlSocialYoutube' => 'http://www.youtube.com/user/acme', 'urlSocialTwitter' => 'https://twitter.com/acme', 'user.passwordResetTokenExpire' => 3600, 'isSignupApprovalRequired' => false, // allows user to signup andlogin right away //'isSignupApprovalRequired' => true, // requires sending email toadmin to request signup approval 'timezone' => 'America/New_York', // Must be a validPHP timezone. See: http://php.net/manual/en/timezones.php 'siteLayout' => 'default', // ['full','default_white', 'default_gray', 'default'] 'authorizenetAPILoginId' => "YOURLOGIN", 'authorizenetTransactionKey' => "YOURKEY", 'authorizenetTestMode' => true, 'authorizenetSandbox' => true, //----------------------------------- // Site Message of the Day (MOTD) //----------------------------------- // --- Hurricane mesg --- //'appMOTD' => '<div class="col-md-6"> // <h3>NOTE<h3> Due to a hurricane hitting our area, // the office will be closed We apologize for the inconvenience.</div> // <div class="col-md-6"> // <h3>NOTA</h3> Debido al huracán afectando nuestra área, la oficinaestará cerrada. // Nuestras disculpas por este inconveniente.</div>', // --- Phone Line Down message --- //'appMOTD' => '<h3>NOTE</h3> Our phone lines arenot available due // to a nationwide phone provider outage. We apologize for theinconvenience.', // --- Memorial Day message --- //'appMOTD' => '<h3>Memorial Day Closure</h3> Ouroffices will be // closed in observance of the Memorial Day holiday. We will resumenormal hours on Monday. ', // --- US Independence/4th July message //'appMOTD' => '<h3>US Independence DayClosure</h3> Our offices // will be closed July 4, in observance of the US Independence Dayholiday.

Page 8: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

// We will resume normal hours on July 5. ', // site Message of the Day // --- Labor Day message --- //'appMOTD' => '<h3>Labor Day Closure</h3> Ouroffices will be // closed in observance of the Labor Day holiday. We will resume normalhours on Tuesday. ', // --- Thanksgiving message --- //'appMOTD' => '<h3>Thanksgiving Holiday</h3> Dueto the // Thanksgiving Day holiday, the office will be closed. We apologize forthe inconvenience. <br/> // Debido a la celebración del Día de Acción de Gracias, la oficinaestará cerrada. // Nuestras disculpas por cualquier molestia.', // site Message of theDay // --- Xmas/NewYear message --- //'appMOTD' => '<h3>Christmas / New Year HolidayClosure</h3> // Our offices will be closed December 25, and January 1, in observanceof the Christmas // and New Year holidays. We will resume normal hours the next day. HappyHolidays!', // --- NewYear message --- //'appMOTD' => '<h3>New Year Holiday Closure</h3>Our offices will be // closed January 1, in observance of the New Year holidays. We willresume normal hours // the next day. Happy Holidays!', // site Message of the Day // Test Site //'appMOTD' => '<h3>TEST SITE</h3> This site is fortesting only.', // --- MOTD Date Range (comment lines to display permanently) --- //'appMOTDStartDate' => '2017-09-07', // Start date (YYYY-MM-DD) //'appMOTDStopDate' => '2017-09-11', // Stop date (YYYY-MM-DD)];

Main/Web Config

/frontend/config/main-local.php and /backend/config/main-local.php (advanced), or/[app]/config/web.php (basic)

return [

Page 9: Yii 2 Setup and Configuration

2021/09/18 22:11 9/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) -this is required by cookie validation. // Must be UNIQUE to project to avoid conflicts. // NOTE: In Advanced app, 'Request' can only be used in frontendor backend. // Do not add to 'common' config. If added to 'common'config, // console commands fail with an exception. // // Preferably, add to local config: // $config['components']['request']['cookieValidationKey'] ='my@s3cr3tk3y_myapp'; 'cookieValidationKey' => 'my secret key goes here (or in web-local.php or main-local.php)_' . $params['appId'], // Use a custom name per app for csrf cookie to avoid clashes withother Yii apps 'csrfParam' => 'csrf_' . $params['appId'], 'csrfCookie' => [ 'httpOnly' => true, ], ], ... 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [] ], //... 'formatter' => [ 'class' => 'yii\i18n\Formatter', 'dateFormat' => 'php:M d, Y', 'datetimeFormat' => 'php:M d, Y H:i:s', 'timeFormat' => 'php:H:i:s', 'defaultTimeZone' => 'America/New_York' ], // To avoid session conflicts with other Yii2 apps 'user' => [ 'identityClass' => 'app\models\User', // for basic app //'identityClass' => 'common\models\User', // for advanced app 'enableAutoLogin' => true, 'identityCookie' => [ 'name' => $params['appId'] . '_User', // unique for app //'path' => '/backend/web' // correct path for the app webfolder.

Page 10: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

], ], 'session' => [ 'name' => $params['appId'] . '_SessionId', // unique for app 'savePath' => __DIR__ . '/../runtime', // a temporary folder forapp ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', // Directory that contains the view files // for composing mail messages. Defaults to '@app/mail' 'viewPath' => '@app/mail', // for basic app //'viewPath' => '@common/mail', // for advanced app // Send all mail messages to a file by default. // The messages get stored locally under '@app/runtime/mail' 'useFileTransport' => true, //'fileTransportPath' => '@runtime/mail', // Send all mail messages as real emails. // Set 'useFileTransport' to false, // and configure a transport for the mailer. //'useFileTransport' => false, //'transport' => [ // 'class' => 'Swift_SmtpTransport', // 'host' => 'smtp.office365.com', // 'username' => '[email protected]', // 'password' => 'mypassword', // 'port' => '587', // 'encryption' => 'tls', //], ], ] //...];

htaccess File

For urlManager component to work correctly using PrettyUrls, you must do this:

1. Configure Apache to run with ''rewrite_module'' turned on.2. Create ''.htaccess'' file.

Edit /etc/apache2/apache.conf file to have permissions for rewrite:

Page 11: Yii 2 Setup and Configuration

2021/09/18 22:11 11/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

<Directory "/path/to/document/root/"> AllowOverride All //...</Directory>

NOTE: Must restart apache server.

Create a .htaccess file in each web folders (/frontend/web and /backend/web) to contain this:

# use mod_rewrite for pretty URL supportRewriteEngine on # HTTPS redirect for pages users input sensitive data (eg. password)# NOTE: Disable these in localhost or other server without HTTPS.#RewriteCond %{HTTPS} off#RewriteCond %{REQUEST_URI} /(login) [NC]#RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L] # If a directory or a file exists, use the request directlyRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d # Otherwise forward the request to index.phpRewriteRule . index.php

System Variables

Setup application name in [app]/vendor/yiisoft/yii2/base/Application.php:

/** * @var string the application name. */public $name = 'My Application';

Debugging

Yii2-debug module needs permission to trace and log in case application is installed on a server otherthan localhost. Edit file [app]/vendor/yiisoft/yii2-debug/Module.php:

class Module extends \yii\base\Module implements BootstrapInterface{ /** * @var array the list of IPs that are allowed to access this module. * Each array element represents a single IP filter which can be either an

Page 12: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

IP address * or an address with wildcard (e.g. 192.168.0.*) to represent a networksegment. * The default value is `['127.0.0.1', '::1']`, which means the module canonly be accessed * by localhost. */ public $allowedIPs = ['127.0.0.1', '::1', '192.168.0.*']; ...}

Even better, just add the settings to your configuration in @app/config/web.php:

if (YII_ENV_DEV) { $config['modules']['debug'] = [ 'class' => 'yii\debug\Module', 'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*'], ];}

Add code snippet to [src]/web/index.php:

if ($_SERVER['HTTP_HOST'] == 'www.example.com') { // Enable Production mode defined('YII_ENV') or define('YII_ENV', 'prod');} else { // Enable Dev mode // comment out the following two lines when deployed to production defined('YII_DEBUG') or define('YII_DEBUG', true); defined('YII_ENV') or define('YII_ENV', 'dev');}

User Authentication / RBAC

For the basic application template, users are added to text file in [app]/models/User.php.For the advanced application template, users and permissions have to be added following thisprocedure:

[app]$ init (if not done so yet to generate the local config files).Edit user table definition in migration script in[app]/console/migrations/m130524_201442_init.php[app]$ yii migrateAdd RBAC support using: Role Based Access Control (RBAC)

Page 13: Yii 2 Setup and Configuration

2021/09/18 22:11 13/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

Basic Template

Main template: Edit /app/views/layouts/main.php:

<head> ... <link rel="shortcut icon" href="<?= Yii::$app->homeUrl; ?>favicon.ico"type="image/x-icon" /></head>... <?php NavBar::begin([ 'brandLabel' => 'Acme Inc.', // if 'companyName' param declared in config/params.php //'brandLabel' => Yii::$app->params['companyName'], // // if 'appName' param declared in config/params.php //'brandLabel' => Yii::$app->params['appName'], // Edit menu as needed ... ?> <!-- Edit footer as needed --> <footer class="footer"> <div class="container"> <p class="pull-left">&copy; Acme Inc. <?= date('Y') ?></p> <!-- if 'companyName' param declared in config/params.php --> <p class="pull-left">&copy; <?= Yii::$app->params['companyName']?> <?= date('Y') ?></p> <p class="pull-right"><?= Yii::powered() ?></p> </div> </footer>>

Frontpage: Edit /app/views/site/index.php:

...//$this->title = 'Acme Application';$this->title = Yii::$app->params['companyName'];...// Edit view as needed...

Page 14: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

Custom Theme

Add theme settings to main configuration. Eg: basic:

...return [ 'components' => [ ... 'view' => [ 'theme' => [ 'basePath' => '@app/themes/basic', // dir containing themedresources (CSS, JS, images, etc.) //'baseUrl' => '@web/themes/basic', // URL for theme if in[app]/web/themes 'baseUrl' => '@web/../themes/basic', // URL for theme if in[app]/themes 'pathMap' => [ '@app/views' => [ // replacement rules of view files '@app/themes/christmas', '@app/themes/basic', ], '@app/modules' => '@app/themes/basic/modules', '@app/widgets' => '@app/themes/basic/widgets', ], ], // Alternatively, use the following: //'layout' => 'mytheme', // `@web/../themes/mytheme/views/` containmytheme.php in this case ],];

Copy [app]/views/layouts and [app]/views/site (and any other folders in views that you wantto override), and place them in @app/themes/basic/views. Copy any required resource folders from[app]/web such as [app]/web/css and [app]/web/js into @app/themes/basic/files.

Edit main layout file [app]/views/layouts/main.phpto include the correct CSS files and themeresources:

...<head> ... <title><?= Html::encode($this->title) ?></title> <?php $this->head() ?> <!-- ### Custom CSS files ### !--> <link rel='stylesheet' href='<?php echo $this->theme->baseUrl;

Page 15: Yii 2 Setup and Configuration

2021/09/18 22:11 15/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

?>/files/css/bootstrap.min.css'/> <link rel='stylesheet' href='<?php echo $this->theme->baseUrl;?>/files/css/custom.min.css'/></head>...

Theme Inheritance

Sometimes you may want to define a basic theme which contains a basic look and feel of the application,and then based on the current holiday, you may want to vary the look and feel slightly. You can achievethis goal using theme inheritance which is done by mapping a single view path to multiple targets. Forexample,

'pathMap' => [ '@app/views' => [ '@app/themes/christmas', '@app/themes/basic', ],]

In this case, the view @app/views/site/index.php would be themed as either@app/themes/christmas/site/index.php or @app/themes/basic/site/index.php, dependingon which themed file exists. If both themed files exist, the first one will take precedence. In practice, youwould keep most themed view files in @app/themes/basic and customize some of them in@app/themes/christmas.

Read more: Yii 2 Output Theming

Gii Configuration

Assuming that [app] can be basic, frontend, backend or common, edit /[app]/config/web.php(Basic) or edit /[app]/config/main.php (Advanced) (See more: Guide Tool: Gii):

return [ ... 'bootstrap' => ['log','gii'], 'modules' => [ 'gii' => [ 'class' => 'yii\gii\Module', 'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*','192.168.178.20'] // adjust this to your needs ], ],

Page 16: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

...];

Alternatively,

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', 'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*'] // adjust this toyour needs ];}

Run Gii

Create Database

Create database and all the necessary tables required by models. You can use phpMyAdmin orHeidiSQL.Follow Yii 2 table and field naming conventions.Follow database building guide.

Run Gii using:

Default URL: http://localhost/myapp/web/index.php?r=giiIf pretty URLs enabled, use the following URL: http://localhost/myapp/web/index.php/giior http://localhost/myapp/web/gii

Generate Models, Controllers and CRUD:

Model Class: Enter fully qualified class name of new or already created Model.Basic: app\models\ProductAdvanced: frontend\models\Product.Note: If your model was generated in the backend, put backend instead of frontend. Eg:backend\models\Products

Search Model Class: Provide search model class. Basic: app\models\ProductSearch, orAdvanced: frontend\models\ProductSearch

Controller Class: Provide controller class to be generated. Basic:

Page 17: Yii 2 Setup and Configuration

2021/09/18 22:11 17/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

app\controllers\ProductController, or Advanced:frontend\controllers\ProductController

Gii Command Line

From command line:

$ ./yii gii/model --tableName=city --modelClass=City

For list of all options:

$ ./yii help gii

Gii CLI Command List (including examples)

Access controller:

Product Add:http://localhost/path/to/frontend/web/index.php?r=products/createProduct Index:http://localhost/path/to/frontend/web/index.php?r=products/index

1. Possible error: Class ''frontend\models\Product'' does not existor has syntax error.2. Solution: In model and controller, replace ''namespaceapp\models'' to ''namespace frontend\models'' or ''namespacebackend\models''

Custom Model Templates

See: Yii2: Creating your own templates

Copy the folder @app/vendor/yiisoft/yii2-gii/generators/model to another location, such as@app/templates/model, and modify template to fit your needs. Eg: add getIds() or getList() inmodel/default/model.php:

<?php//... /** * @return \yii\db\ActiveQuery */ public static function get<?php echo $className; ?>List() { $models = self::find()->orderBy(['id'=> SORT_ASC])->all(); return \yii\helpers\ArrayHelper::map($models, 'id', 'name');

Page 18: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

}//...

Tell Gii about the custom template. The setting is made in the config file:

// config/web.php for basic app// ...if (YII_ENV_DEV) { $config['modules']['gii'] = [ 'class' => 'yii\gii\Module', 'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'], // Custom Generator + Template 'generators' => [ // custom generators 'model' => [ // generator type: 'model' //'class' => 'yii\gii\generators\model\Generator', // defaultgenerator class 'class' => 'app\templates\model\Generator', // customgenerator class 'templates' => [ //setting for custom templates 'model' => '@app/vendor/yiisoft/yii2-gii/generators/model/default', // template name => path to template 'myModel' => '@app/templates/model/default', // templatename => path to template ] ], //... ], ];}

Edit the app\templates\model\Generator file to adjust the namespace and name of generator.

namespace app\templates\model;//... class Generator extends \yii\gii\Generator{ /** * {@inheritdoc} */ public function getName() { return 'MY MODEL Generator'; } /** * {@inheritdoc}

Page 19: Yii 2 Setup and Configuration

2021/09/18 22:11 19/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

*/ public function getDescription() { return 'My MODEL Generator. Custom Model generator based on thedefault. This generator generates an ActiveRecord class for the specifieddatabase table.'; } //...}

If using only a custom template, open the default Gii Model generator, and the custom template shouldbe in the field Code Template. If using a custom generator + template, open Gii and choose thegenerator from that screen (Eg. “myModel”).

Custom CRUD Templates

See: Yii2: Creating your own templates

Copy the folder @app/vendor/yiisoft/yii2-gii/generators/crud to another location, such as@app/templates/crud, and modify template to fit your needs. Eg: add errorSummary() inviews/_form.php:

<?php//...<div class="<?=Inflector::camel2id(StringHelper::basename($generator->modelClass)) ?>-form"> <?= "<?php " ?>$form = ActiveForm::begin(); ?> <?= "<?=" ?> $form->errorSummary($model) ?> <!-- ADDED HERE -->//...

Tell Gii about custom template. The setting is made in the config file:

// config/web.php for basic app// ...if (YII_ENV_DEV) { $config['modules']['gii'] = [ 'class' => 'yii\gii\Module', 'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'], // Custom Template (using default generator) //'generators' => [ // 'crud' => [ // generator name: 'crud' (to override default) // 'class' => 'yii\gii\generators\crud\Generator', // defaultgenerator class // 'templates' => [ //setting for out templates

Page 20: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

// 'myCrud' => '@app/templates/crud/default', // templatename => path to template // ] // ], //], // Custom Generator + Template 'generators' => [ // custom generators 'crud' => [ // generator type: 'crud' 'class' => 'app\templates\crud\Generator', //custom generator class 'templates' => [ //setting for out templates 'crud' => '@app/vendor/yiisoft/yii2-gii/generators/crud/default', // template name => path to template 'myCrud' => '@app/templates/crud/default', //template name => path to template ] ] ], ];}

Edit the app\templates\crud\Generator file to adjust the namespace and name of generator.

namespace app\templates\crud;//... class Generator extends \yii\gii\Generator{ /** * {@inheritdoc} */ public function getName() { return 'MY CRUD Generator'; } /** * {@inheritdoc} */ public function getDescription() { return 'My CRUD Generator. Custom CRUD generator based on the default.This generator generates a controller and views that implement CRUD (Create,Read, Update, Delete) operations for the specified data model.'; }

Page 21: Yii 2 Setup and Configuration

2021/09/18 22:11 21/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

//...}

If using only a custom template, open the default Gii CRUD generator, and the custom template shouldbe in the field Code Template. If using a custom generator + template, open Gii and choose thegenerator from that screen (Eg. “myCrud”).

Shared Hosting

To set up as a shared hosting for both the front and backend using the advanced site:

Move frontend/web content to the public www or public_html folder in your shared host.Move backend/web content to an admin folder inside the public www or public_html folder inyour shared host, such as www/admin.For each folder, adjust the paths accordingly in index.php and index-test.php.

Edit file backend/config/main.php as follows:

'components' => [ 'request' => [ // Use a custom name per app for csrf cookie to avoid clashes withother Yii apps 'csrfParam' => '_csrf-backend_' . $params['appId'], 'csrfCookie' => [ 'httpOnly' => true, 'path' => '/admin', ], ], 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => true, 'identityCookie' => [ 'name' => '_identity-backend', 'path' => '/admin', 'httpOnly' => true, ], ], 'session' => [ // this is the name of the session cookie used for login on thebackend 'name' => 'advanced-backend', 'cookieParams' => [ 'path' => '/admin', ],

Page 22: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

],],

Test the setup:

Visit frontend: http://localhost/myapp/Visit backend: http://localhost/myapp/admin/

Reference:

Guide Advanced App in Shared Hosting

Custom Domains

To set up custom domains for both the front and backend using the advanced site, edit the followingfiles:

# /etc/hosts127.0.0.1 example.com127.0.0.1 admin.example.com

Using a virtual hosts:

# /etc/apache2/sites-available/example.conf<VirtualHost example.com:80> ServerAdmin [email protected] ServerName example.com DocumentRoot "C:/wamp/www/yii/advanced/frontend/web" <Directory "C:/wamp/www/yii/advanced/frontend/web"> Require all granted </Directory> Alias /frontend "C:/wamp/www/yii/advanced/frontend/web" <Directory "C:/wamp/www/yii/advanced/frontend/web"> Require all granted </Directory></VirtualHost>

# /etc/apache2/sites-available/admin.example.conf<VirtualHost admin.example.com:80> ServerAdmin [email protected] ServerName admin.example.com DocumentRoot "C:/wamp/www/yii/advanced/backend/web" <Directory "C:/wamp/www/yii/advanced/backend/web"> Require all granted </Directory>

Page 23: Yii 2 Setup and Configuration

2021/09/18 22:11 23/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

Alias /backend "C:/wamp/www/yii/advanced/backend/web" <Directory "C:/wamp/www/yii/advanced/backend/web"> Require all granted </Directory></VirtualHost>

Alternatively, simply using aliases:

# /etc/apache2/conf.d/example.confAlias /frontend "C:/wamp/www/yii/advanced/frontend/web"<Directory "C:/wamp/www/yii/advanced/frontend/web"> Require all granted</Directory>

# /etc/apache2/conf.d/admin.example.confAlias /backend "C:/wamp/www/yii/advanced/backend/web"<Directory "C:/wamp/www/yii/advanced/backend/web"> Require all granted</Directory>

Restart apache and visit:

Frontend: http://example.comBackend: http://admin.example.com

Rewrite Base URL (/basic/web or/frontend/web)

References:

Simple mod_rewritemod_rewrite Tips and TripsApache 2.4 mod_rewriteApache 2.4 mod_rewrite IntroductionApache 2.4 mod_rewrite Flagsmod_rewrite Cheat Sheetmod_rewrite Variables CheatsheetRegex SymbolsHosting Advanced Yii2 App

Webserver Alias Approach (Recommended)

Page 24: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

Edit the apache config file httpd.conf to include the web folder as part of the aliased document root:

<IfModule alias_module> # # Redirect: Allows you to tell clients about documents that used to # exist in your server's namespace, but do not anymore. The client # will make a new request for the document at its new location. # Example: # Redirect permanent /foo http://www.example.com/bar # # Alias: Maps web paths into filesystem paths and is used to # access content that does not live under the DocumentRoot. # Example: # Alias /webpath /full/filesystem/path Alias /churchhub "D:/proj/mychurch/church-hub/web" # ... </IfModule> <Directory "D:/proj/mychurch/church-hub/web"> # use mod_rewrite for pretty URL support RewriteEngine on # if $showScriptName is false in UrlManager, do not allow accessing URLswith script name RewriteRule ^index.php/ - [L,R=404] # If a directory or a file exists, use the request directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Otherwise forward the request to index.php RewriteRule . index.php # Other Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted</Directory>

Then:

Restart your apache web server.Point your browser to your new alias to test the URL. That's it.

Page 25: Yii 2 Setup and Configuration

2021/09/18 22:11 25/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

Basic App

Create .htaccess file in [yiiroot] folder:

Options -Indexes <IfModule mod_rewrite.c> Options +FollowSymLinks IndexIgnore */* RewriteEngine on # prevents all requests that are not directed at the # public directory to be routed to /web/. # if request does not start with web, add it. RewriteCond %{REQUEST_URI} !^public RewriteRule ^(.*)$ web/$1 [L] # if file or directory does not exists, go to /web/index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d #RewriteRule . /web/index.php RewriteRule . index.php</IfModule> # Deny accessing below extensions<Files ~ "(.json|.lock|.git)">Order allow,denyDeny from all</Files> # Deny accessing dot filesRewriteRule (^\.|/\.) - [F]

Example:

htaccess

Options -Indexes <IfModule mod_rewrite.c> RewriteEngine on # Prevents all requests that are not directed at the # media, api, and assets directories to be routed to /web/. #RewriteCond %{REQUEST_URI} !/(media) RewriteCond %{REQUEST_URI} !/(api)

Page 26: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

RewriteCond %{REQUEST_URI} !/(assets) RewriteRule ^(.*)$ web/$1 [NC,L] # Rewrites all requests to /media directory # to be routed to /web/media/. #RewriteCond %{REQUEST_URI} /(media) #RewriteRule media/(.*)$ web/media/$1 [NC,L] # Rewrites all requests to /api directory # to be routed to /api/web/. RewriteCond %{REQUEST_URI} /(api) RewriteRule api/(.*)$ api/web/$1 [NC,L] # Rewrites all requests to /assets directory # to be routed to /web/assets/. RewriteCond %{REQUEST_URI} /(assets) RewriteRule assets/(.*)$ web/assets/$1 [NC,L] </IfModule> # Deny accessing extensions listed below<Files ~ "(.json|.lock|.git)">Order allow,denyDeny from all</Files> <IfModule mod_rewrite.c> # Deny accessing dot files RewriteRule (^\.|/\.) - [F]</IfModule>

Create .htaccess file in [yiiroot]/web/ folder:

RewriteEngine on # Is the request for a non-existent file?RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php

Hide the web folder. Edit [yiiroot]/config/web.php file to include the following:

<?php...

Page 27: Yii 2 Setup and Configuration

2021/09/18 22:11 27/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

use \yii\web\Request; // Set current location to be root directory, i.e. '/web' becomes '/'// Mod_Rewrite procedure will send traffic to '/' if files are in'/var/www/html'$baseUrl = str_replace('/web', '', (new \yii\web\Request)->getBaseUrl()); return [$config = [ 'id' => 'basic', 'homeUrl' => $baseUrl . "/", // define home //... 'components' => [ 'request' => [ // Define request. Must have a baseUrl specified. // Required if wanting to hide 'web' folder from url. 'baseUrl' => $baseUrl, //... ], // Activate urlManager. Must have baseUrl specified. 'urlManager' => [ 'baseUrl' => $baseUrl, 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [] ], //... ], 'params' => $params,];

Advanced App

Rewrite Frontend URLs to be simpler. We do not care about the Backend URLs because those are not forpublic consumption.

Create .htaccess file in [yiiroot] folder:

Options -Indexes <IfModule mod_rewrite.c> RewriteEngine on

Page 28: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

# prevents all requests that are not directed at the # public directory to be routed to /frontend/web/. # if request does not start with web, add it. RewriteCond %{REQUEST_URI} !^public RewriteRule ^(.*)$ frontend/web/$1 [L]</IfModule> # Deny accessing below extensions<Files ~ "(.json|.lock|.git)">Order allow,denyDeny from all</Files> # Deny accessing dot filesRewriteRule (^\.|/\.) - [F]

Alternatively, for Advanced Applications:

Options +FollowSymLinksIndexIgnore */*RewriteEngine on # Do not apply rewrite to '/av' or 'av-test'#RewriteRule ^(av|av-test)($|/) - [L]RewriteCond %{REQUEST_URI} !^/av/$RewriteCond %{REQUEST_URI} !^/av-test/$ # if request begins with /admin, remove admin and add /backend/web/RewriteCond %{REQUEST_URI} ^/adminRewriteRule ^admin\/?(.*) /backend/web/$1 # other requests add /frontend/web/$1RewriteCond %{REQUEST_URI} !^/(frontend/web|backend/web|admin)RewriteRule (.*) /frontend/web/$1 # if frontend requestRewriteCond %{REQUEST_URI} ^/frontend/webRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule . /frontend/web/index.php # if backend requestRewriteCond %{REQUEST_URI} ^/backend/webRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule . /backend/web/index.php

Page 29: Yii 2 Setup and Configuration

2021/09/18 22:11 29/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

Create .htaccess file in [yiiroot]/frontend/web/ folder:

RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php

Edit [yiiroot]/frontend/config/main.php file to include the following:

<?php... use \yii\web\Request; // Alternative 1 (for any URL)// Use current location as root, i.e. '/frontend/web' becomes '/'// The Rewrite procedure to send traffic to '/' if files are in'/var/www/html'$baseUrl = str_replace('/frontend/web', '', (new\yii\web\Request)->getBaseUrl()); // Alternative 2 (optional for specific URLs)// The Rewrite procedure to send traffic to '/blog' if files are in'/var/www/html/blog'//$baseUrl = str_replace('/blog/frontend/web', '/blog/', (new\yii\web\Request)->getBaseUrl()); return [ 'id' => 'app-frontend', ... 'components' => [ // Define request. Must have a baseUrl specified 'request' => [ 'baseUrl' => $baseUrl, //'baseUrl' => '/', // or manually set it to '/' //'baseUrl' => '/blog', // or manually set it to '/blog' ], // Define urlManager. Must have a baseUrl specified 'urlManager' => [ 'baseUrl' => $baseUrl, //'baseUrl' => '/', // or manually set it to '/' //'baseUrl' => '/blog', // or manually set it to '/blog' 'enablePrettyUrl' => true,

Page 30: Yii 2 Setup and Configuration

Last update: 2021/09/1514:32 tutorial:yii2:setup_and_configuration https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

https://circ.cs.southern.edu/wiki/ Printed on 2021/09/18 22:11

'showScriptName' => false, 'rules' => [] ], ... ], 'params' => $params,];

To enable mod_rewrite logging to trace through .htaccess settings, use this in Appache confighttpd.conf:

<IfModule mod_rewrite.c> # mod_rewrite 2.2 # Log to a file: #RewriteLog "c:/wamp/logs/rewrite.log" #RewriteLogLevel 3 # mod_rewrite 2.4 LogLevel alert rewrite:trace3</IfModule>

Configuring Different Sessions forAuthentication to Separate Yii Apps

You can configure different identity cookies and sessions for your user component for frontend andbackend app or totally different Yii apps. Note the unique name property in identityCookie.

Backend Config

// in backend/config/main.php$config = [ ... 'components' => [ 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, 'identityCookie' => [ 'name' => $params['appId'] . '_backendUser', // unique forbackend //'path'=>'/backend/web' // correct path for the backend app. ] ],

Page 31: Yii 2 Setup and Configuration

2021/09/18 22:11 31/31 Yii 2 Setup and Configuration

CIRC Wiki - https://circ.cs.southern.edu/wiki/

'session' => [ 'name' => $params['appId'] . '_backendSessionId', // unique forbackend 'savePath' => __DIR__ . '/../runtime', // a temporary folder onbackend ], ]];

Frontend Config

// in frontend/config/main.php$config = [ ... 'components' => [ 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, 'identityCookie' => [ 'name' => $params['appId'] . '_frontendUser', // unique forfrontend //'path'=>'/frontend/web' // correct path for the frontendapp. ] ], 'session' => [ 'name' => $params['appId'] . '_frontendSessionId', // unique forfrontend 'savePath' => __DIR__ . '/../runtime', // a temporary folder onfrontend ], ]];

See Also:

Yii 2.0: Configuring different sessions for backend and frontend in Yii advanced app

From:https://circ.cs.southern.edu/wiki/ - CIRC Wiki

Permanent link:https://circ.cs.southern.edu/wiki/doku.php?id=tutorial:yii2:setup_and_configuration

Last update: 2021/09/15 14:32