Yii – Aliases

Yii – Aliases ”; Previous Next Aliases help you not to hard-code absolute paths or URLs in your project. An alias starts with the @ character. To define an alias you should call the Yii::setAlias() method − // an alias of a file path Yii::setAlias(”@alias”, ”/path/to/alias”); // an alias of a URL Yii::setAlias(”@urlAlias”, ”http://www.google.com”); You can also derive a new alias from an existing one − Yii::setAlias(”@pathToSomewhere”, ”@alias/path/to/somewhere”); You can call the Yii::setAlias() method in the entry script or in a writable property called aliases in the application configuration − $config = [ ”id” => ”basic”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”], ”components” => [ ”aliases” => [ ”@alias” => ”/path/to/somewhere”, ”@urlAlias” => ”http://www.google.com”, ], //other components… ] ] To resolve alias, you should call the Yii::getAlias() method. Yii predefines the following aliases − @app − The base path of the application. @yii − The folder where the BaseYii.php file is located. @webroot − The Web root directory of the application. @web − The base URL of the application. @runtime − The runtime path of the application. Defaults to @app/runtime. @vendor − The Composer vendor directory. Defaults to @app/vendor. @npm − The root directory for npm packages. Defaults to @vendor/npm. @bower − The root directory for bower packages. Defaults to @vendor/bower. Now, add a new function called actionAliases() to the SiteController − public function actionAliases() { Yii::setAlias(“@components”, “@app/components”); Yii::setAlias(“@imagesUrl”, “@web/images”); var_dump(Yii::getAlias(“@components”)); var_dump(Yii::getAlias(“@imagesUrl”)); } In the above code, we created two aliases: @components for application components and @imagesUrl for URL where we stored all application images. Type http://localhost:8080/index.php?r=site/aliases, you will see the following output − Print Page Previous Next Advertisements ”;

Yii – Cookies

Yii – Cookies ”; Previous Next Cookies are plain text files stored on the client side. You can use them for tracking purpose. There are three steps to identify a returning user − Server sends a set of cookies to the client (browser). For example, id or token. Browser stores it. Next time a browser sends a request to the web server, it also sends those cookies, so that the server can use that information to identify the user. Cookies are usually set in an HTTP header as shown in the following code. HTTP/1.1 200 OK Date: Fri, 05 Feb 2015 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name = myname; expires = Monday, 06-Feb-16 22:03:38 GMT; path = /; domain = tutorialspoint.com Connection: close Content-Type: text/html PHP provides the setcookie() function to set cookies − setcookie(name, value, expire, path, domain, security); where − name − Sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. value − Sets the value of the named variable. expiry − Specifies a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. path − Specifies the directories for which the cookie is valid. domain − This can be used to define the domain name in very large domains. All cookies are only valid for the host and domain which created them. security − If set to, it means that the cookie should only be sent by HTTPS, otherwise, when set to 0, cookie can be sent by regular HTTP. To access cookies in PHP, you may use the $_COOKIE or $HTTP_COOKIE_VARS variables. <?php echo $_COOKIE[“token”]. “<br />”; /* is equivalent to */ echo $HTTP_COOKIE_VARS[“token”]. “<br />”; echo $_COOKIE[“id”] . “<br />”; /* is equivalent to */ echo $HTTP_COOKIE_VARS[“id”] . “<br />”; ?> To delete a cookie, you should set the cookie with a date that has already expired. <?php setcookie( “token”, “”, time()- 60, “/”,””, 0); setcookie( “id”, “”, time()- 60, “/”,””, 0); ?> Print Page Previous Next Advertisements ”;

Yii – Fragment Caching

Yii – Fragment Caching ”; Previous Next Fragment caching provides caching of a fragment of a web page. Step 1 − Add a new function called actionFragmentCaching() to the SiteController. public function actionFragmentCaching() { $user = new MyUser(); $user->name = “cached user name”; $user->email = “[email protected]”; $user->save(); $models = MyUser::find()->all(); return $this->render(”cachedview”, [”models” => $models]); } In the above code, we created a new user and displayed a cachedview view file. Step 2 − Now, create a new file called cachedview.php in the views/site folder. <?php if ($this->beginCache(”cachedview”)) { ?> <?php foreach ($models as $model): ?> <?= $model->id; ?> <?= $model->name; ?> <?= $model->email; ?> <br/> <?php endforeach; ?> <?php $this->endCache(); } ?> <?php echo “Count:”, appmodelsMyUser::find()->count(); ?> We have enclosed a content generation logic in a pair of beginCache() and endCache() methods. If the content is found in cache, the beginCache() method will render it. Step 3 − Go to the URL http://localhost:8080/index.php?r=site/fragment-caching and reload the page. Following will be the output. Notice, that the content between the beginCache() and endCache() methods is cached. In the database, we have 13 users but only 12 are displayed. Page Caching Page caching provides caching the content of a whole web page. Page caching is supported by yiifilterPageCache. Step 1 − Modify the behaviors() function of the SiteController. public function behaviors() { return [ ”access” => [ ”class” => AccessControl::className(), ”only” => [”logout”], ”rules” => [ [ ”actions” => [”logout”], ”allow” => true, ”roles” => [”@”], ], ], ], ”verbs” => [ ”class” => VerbFilter::className(), ”actions” => [ ”logout” => [”post”], ], ], [ ”class” => ”yiifiltersPageCache”, ”only” => [”index”], ”duration” => 60 ], ]; } The above code caches the index page for 60 seconds. Step 2 − Go to the URL http://localhost:8080/index.php?r=site/index. Then, modify the congratulation message of the index view file. If you reload the page, you will not notice any changes because the page is cached. Wait a minute and reload the page again. HTTP Caching Web applications can also use client-side caching. To use it, you may configure the yiifilterHttpCache filter for controller actions. The Last-Modified header uses a timestamp to indicate whether the page has been modified. Step 1 − To enable sending the Last-Modified header, configure the yiifilterHttpCache::$lastModified property. public function behaviors() { return [ [ ”class” => ”yiifiltersHttpCache”, ”only” => [”index”], ”lastModified” => function ($action, $params) { $q = new yiidbQuery(); return $q->from(”news”)->max(”created_at”); }, ], ]; } In the above code, we enabled the HTTP caching only for the index page. When a browser opens the index page for the first time, the page is generated on the server side and sent to the browser. The second time, if no news is created, the server will not regenerate the page. The Etag header provides a hash representing the content of the page. If the page is changed, the hash will be changed as well. Step 2 − To enable sending the Etag header, configure the yiifiltersHttpCache::$etagSeed property. public function behaviors() { return [ [ ”class” => ”yiifiltersHttpCache”, ”only” => [”index”], ”etagSeed” => function ($action, $params) { $user = $this->findModel(Yii::$app->request->get(”id”)); return serialize([$user->name, $user->email]); }, ], ]; } In the above code, we enabled the HTTP caching for the index action only. It should generate the Etag HTTP header based on the name and email of the user. When a browser opens the index page for the first time, the page is generated on the server side and sent to the browser. The second time, if there are no changes to the name or email, the server will not regenerate the page. Print Page Previous Next Advertisements ”;

Yii – Database Migration

Yii – Database Migration ”; Previous Next During the developing of a database-driven application, the database structure evolves with the source code. Yii provides the database migration feature that allows you to keep track of database changes. Yii provides the following migration command line tools − Create new migrations Revert migrations Apply migrations Re-apply migrations Show migration status and history Creating a Migration Let us create a new database migration. Step 1 − Inside the project root of the basic application template open the console window and run. ./yii migrate/create add_news_table The above command will create a new migration file (m160113_102634_add_news_table.php in this case) in the migrations folder. The file contains the following code − <?php use yiidbSchema; use yiidbMigration; class m160113_102634_add_news_table extends Migration { public function up() { } public function down() { echo “m160113_102634_add_news_table cannot be reverted.n”; return false; } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ } ?> Each DB migrations is a PHP class extending the yiidbMigration class. The class name is generated in the following format − m<YYMMDD_HHMMSS>_<Name> where <YYMMDD_HMMSS> is the UTC datetime at which the migration command was executed and <Name> is the argument you provided in the console command. The up() method is invoked when you upgrade your database, while the down() method is called when you downgrade it. Step 2 − To add a new table to the database, modify the migration file this way. <?php use yiidbSchema; use yiidbMigration; class m160113_102634_add_news_table extends Migration { public function up() { $this->createTable(“news”, [ “id” => Schema::TYPE_PK, “title” => Schema::TYPE_STRING, “content” => Schema::TYPE_TEXT, ]); } public function down() { $this->dropTable(”news”); } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ } ?> In the above code we created a new table called news in the up() method and dropped this table in the down() method. The news table consists of three fields: id, title, and content. When creating a table or a column we should use abstract types so that migrations are independent of a database type. For example, in the case of MySQL, TYPE_PK will be converted into int(11) NOT NUL AUTO_INCREMETN PRIMARY KEY. Step 3 − To upgrade a database, run this command. ./yii migrate The above command will list all available migrations that have not been applied yet. Then, if you confirm to apply migrations, it will run safeUp() or up() in all new migration classes. Step 4 − To apply only three available migrations, you may run. ./yii migrate 3 Step 5 − You can also define a particular migration the database should be migrated to. # using timestamp to specify the migration yii migrate/to 160202_195501 # using a string that can be parsed by strtotime() yii migrate/to “2016-01-01 19:55:01″ # using full name yii migrate/to m160202_195501_create_news_table # using UNIX timestamp yii migrate/to 1393964718 Step 6 − To revert a migration(execute down() or safeDown() methods), run. ./yii migrate/down Step 7 − To revert the most five recently applied migrations, you may run. ./yii migrate/down 5 Step 8 − To redo(revert and then apply again) migrations, run. ./yii migrate/redo To list the migrations already applied, use these commands − yii migrate/new # shows the first 10 new migrations yii migrate/new 3 # shows the first 3 new migrations yii migrate/new all # shows all new migrations yii migrate/history # shows the last 10 applied migrations yii migrate/history 20 # shows the last 20 applied migrations yii migrate/history all # shows all applied migrations Sometimes you need to add or drop a column from a specific table. You can use addColumn() and dropColumn() methods. Step 1 − Create a new migration. ./yii migrate/create add_category_to_news Step 2 − Modify the newly created migration file this way. <?php use yiidbSchema; use yiidbMigration; class m160113_110909_add_category_to_news extends Migration { public function up() { $this->addColumn(”news”, ”category”, $this->integer()); } public function down() { $this->dropColumn(”news”, ”category”); } } ?> Now, if you run ./yii migrate, the category column should be added to the news table. On the contrary, if you run ./yii migrate/down 1, the category column should be dropped. When performing DB migrations, it is important to ensure each migration has succeded or failed. It is recommended to enclose DB operations in a transaction. To implement transactional migrations, you should just put the migration code in the safeUp() and safeDown() methods. If any operation in these methods fails, all previous operations will be rolled back. The previous example in the “transactional way” will be − <?php use yiidbSchema; use yiidbMigration; class m160113_110909_add_category_to_news extends Migration { public function safeUp() { $this->addColumn(”news”, ”category”, $this->integer()); } public function safeDown() { $this->dropColumn(”news”, ”category”); } } ?> The yiidbMigration class provides the following methods for manipulating databases − execute() − Executes a raw SQL statement createTable() − Creates a table renameTable() − Renames a table insert() − Inserts a single row batchInsert() − Inserts multiple rows update() − Updates rows delete() − Deletes rows addColumn() − Adds a column renameColumn() − Renames a column dropColumn() − Removes a column alterColumn() − Alters a column dropTable() − Removes a table truncateTable() − Removes all rows in a table createIndex() − Creates an index dropIndex() − Removes an index addPrimaryKey() − Adds a primary key dropPrimaryKey() − Removes a primary key addForeignKey() − Adds a foreign key dropForeignKey() − Removes a foreign key Print Page Previous Next Advertisements ”;

Yii – Data Widgets

Yii – Data Widgets ”; Previous Next Yii provides a set of widgets for displaying data. You can use the DetailView widget to display a single record. The ListView widget, as well as Grid View, can be used to display a table of records with features like filtering, sorting, and pagination. Preparing the DB Step 1 − Create a new database. Database can be prepared in the following two ways. In the terminal run mysql -u root –p Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci; Step 2 − Configure the database connection in the config/db.php file. The following configuration is for the system used currently. <?php return [ ”class” => ”yiidbConnection”, ”dsn” => ”mysql:host=localhost;dbname=helloworld”, ”username” => ”vladimir”, ”password” => ”12345”, ”charset” => ”utf8”, ]; ?> Step 3 − Inside the root folder run./yii migrate/create test_table. This command will create a database migration for managing our DB. The migration file should appear in the migrations folder of the project root. Step 4 − Modify the migration file (m160106_163154_test_table.php in this case) this way. <?php use yiidbSchema; use yiidbMigration; class m160106_163154_test_table extends Migration { public function safeUp() { $this->createTable(“user”, [ “id” => Schema::TYPE_PK, “name” => Schema::TYPE_STRING, “email” => Schema::TYPE_STRING, ]); $this->batchInsert(“user”, [“name”, “email”], [ [“User1”, “[email protected]”], [“User2”, “[email protected]”], [“User3”, “[email protected]”], [“User4”, “[email protected]”], [“User5”, “[email protected]”], [“User6”, “[email protected]”], [“User7”, “[email protected]”], [“User8”, “[email protected]”], [“User9”, “[email protected]”], [“User10”, “[email protected]”], [“User11”, “[email protected]”], ]); } public function safeDown() { $this->dropTable(”user”); } } ?> The above migration creates a user table with these fields: id, name, and email. It also adds a few demo users. Step 5 − Inside the project root run./yii migrate to apply the migration to the database. Step 6 − Now, we need to create a model for our user table. For the sake of simplicity, we are going to use the Gii code generation tool. Open up this url: http://localhost:8080/index.php?r=gii. Then, click the “Start” button under the “Model generator” header. Fill in the Table Name (“user”) and the Model Class(“MyUser”), click the “Preview” button and finally, click the “Generate” button. The MyUser model should appear in the models directory. DetailView Widget The DetailView widget shows the data of a single model. The $attributes property defines which model attributes should be displayed. Step 1 − Add the actionDataWidget method to the SiteController. public function actionDataWidget() { $model = MyUser::find()->one(); return $this->render(”datawidget”, [ ”model” => $model ]); } In the above code, we find that the first MyUser model and pass it to the datawidget view. Step 2 − Create a file called datawidget.php inside the views/site folder. <?php use yiiwidgetsDetailView; echo DetailView::widget([ ”model” => $model, ”attributes” => [ ”id”, //formatted as html ”name:html”, [ ”label” => ”e-mail”, ”value” => $model->email, ], ], ]); ?> Step 3 − If you go to http://localhost:8080/index.php?r=site/data-widget, you will see a typical usage of the DetailView widget. Print Page Previous Next Advertisements ”;

Yii – Properties

Yii – Properties ”; Previous Next Class member variables in PHP are also called properties. They represent the state of class instance. Yii introduces a class called yiibaseObject. It supports defining properties via getter or setter class methods. A getter method starts with the word get. A setter method starts with set. You can use properties defined by getters and setters like class member variables. When a property is being read, the getter method will be called. When a property is being assigned, the setter method will be called. A property defined by a getter is read only if a setter is not defined. Step 1 − Create a file called Taxi.php inside the components folder. <?php namespace appcomponents; use yiibaseObject; class Taxi extends Object { private $_phone; public function getPhone() { return $this->_phone; } public function setPhone($value) { $this->_phone = trim($value); } } ?> In the code above, we define the Taxi class derived from the Object class. We set a getter – getPhone() and a setter – setPhone(). Step 2 − Now, add an actionProperties method to the SiteController. public function actionProperties() { $object = new Taxi(); // equivalent to $phone = $object->getPhone(); $phone = $object->phone; var_dump($phone); // equivalent to $object->setLabel(”abc”); $object->phone = ”79005448877”; var_dump($object); } In the above function we created a Taxi object, tried to access the phone property via the getter, and set the phone property via the setter. Step 3 − In your web browser, type http://localhost:8080/index.php?r=site/properties, in the address bar, you should see the following output. Print Page Previous Next Advertisements ”;

Yii – Formatting

Yii – Formatting ”; Previous Next To display data in a readable format, you can use the formatter application component. Step1 − Add the actionFormatter method to the SiteController. public function actionFormatter(){ return $this->render(”formatter”); } In the above code, we just render the formatter view. Step 2 − Now, create a formatter.php view file inside the views/site folder. <?php $formatter = Yii::$app->formatter; // output: January 1, 2016 echo $formatter->asDate(”2016-01-01”, ”long”),”<br>”; // output: 51.50% echo $formatter->asPercent(0.515, 2),”<br>”; // output: <a href = “mailto:[email protected]”>[email protected]</a> echo $formatter->asEmail(”[email protected]”),”<br>”; // output: Yes echo $formatter->asBoolean(true),”<br>”; // output: (Not set) echo $formatter->asDate(null),”<br>”; ?> Step 3 − Go to http://localhost:8080/index.php?r=site/formatter, you will see the following output. The formatter component supports the following formats related with date and time − Output format Example date January 01, 2016 time 16:06 datetime January 01, 2016 16:06 timestamp 1512609983 relativeTime 1 hour ago duration 5 minutes Step 4 − Modify the formatter view this way. <?php $formatter = Yii::$app->formatter; echo $formatter->asDate(date(”Y-m-d”), ”long”),”<br>”; echo $formatter->asTime(date(“Y-m-d”)),”<br>”; echo $formatter->asDatetime(date(“Y-m-d”)),”<br>”; echo $formatter->asTimestamp(date(“Y-m-d”)),”<br>”; echo $formatter->asRelativeTime(date(“Y-m-d”)),”<br>”; ?> Step 5 − Type http://localhost:8080/index.php?r=site/formatter in the address bar of your web browser, you will see the following output. Date Formats There are also four date format shortcuts: short, medium, long, and full. Step 1 − Modify the formatter view file this way. <?php $formatter = Yii::$app->formatter; echo $formatter->asDate(date(”Y-m-d”), ”short”),”<br>”; echo $formatter->asDate(date(”Y-m-d”), ”medium”),”<br>”; echo $formatter->asDate(date(”Y-m-d”), ”long”),”<br>”; echo $formatter->asDate(date(”Y-m-d”), ”full”),”<br>”; ?> Step 2 − If you go to the web browser and type http://localhost:8080/index.php?r=site/formatter, you will see the following output. Number Formats The formatter component supports the following formats related with numbers − Output format Example integer 51 decimal 105.51 percent 51% scientific 1.050000E+2 currency $105 size 105 bytes shortSize 105 B Step 1 − Modify the formatter view this way. <?php $formatter = Yii::$app->formatter; echo Yii::$app->formatter->asInteger(105),”<br>”; echo Yii::$app->formatter->asDecimal(105.41),”<br>”; echo Yii::$app->formatter->asPercent(0.51),”<br>”; echo Yii::$app->formatter->asScientific(105),”<br>”; echo Yii::$app->formatter->asCurrency(105, “$”),”<br>”; echo Yii::$app->formatter->asSize(105),”<br>”; echo Yii::$app->formatter->asShortSize(105),”<br>”; ?> Step 2 − Go to http://localhost:8080/index.php?r=site/formatter, you will see the following output. Other Formats Yii also supports other formats − text − The value is HTML-encoded. raw − The value is outputted as is. paragraphs − The value is formatted as HTML text paragraphs wrapped into the p tag. ntext − The value is formatted as an HTML plain text where newlines are converted into line breaks. html − The value is purified using HtmlPurifier to avoid XSS attacks. image − The value is formatted as an image tag. boolean − The value is formatted as a boolean. url − The value is formatted as a link. email − The value is formatted as a mailto-link. The formatter may use the currently active locale to determine how to format a value for a specific country. The following example shows how to format date for different locales. <?php Yii::$app->formatter->locale = ”ru-RU”; echo Yii::$app->formatter->asDate(”2016-01-01”); // output: 1 января 2016 г. Yii::$app->formatter->locale = ”de-DE”; // output: 1. Januar 2016 echo Yii::$app->formatter->asDate(”2016-01-01”); Yii::$app->formatter->locale = ”en-US”; // output: January 1, 2016 echo Yii::$app->formatter->asDate(”2016-01-01”); ?> Print Page Previous Next Advertisements ”;

Yii – Using Flash Data

Yii – Using Flash Data ”; Previous Next Yii provides a concept of flash data. Flash data is a session data which − Is set in one request. Will only be available on the next request. Will be automatically deleted afterwards. Step 1 − Add an actionShowFlash method to the SiteController. public function actionShowFlash() { $session = Yii::$app->session; // set a flash message named as “greeting” $session->setFlash(”greeting”, ”Hello user!”); return $this->render(”showflash”); } Step 2 − Inside the views/site folder, create a View file called showflash.php. <?php use yiibootstrapAlert; echo Alert::widget([ ”options” => [”class” => ”alert-info”], ”body” => Yii::$app->session->getFlash(”greeting”), ]); ?> Step 3 − When you type http://localhost:8080/index.php?r=site/show-flash in the address bar of the web browser, you will see the following. Yii also provides the following session classes − yiiwebCacheSession − Stores session information in a cache. yiiwebDbSession − Stores session information in a database. yiimongodbSession − Stores session information in a MongoDB. yiiredisSession − Stores session information using redis database. Print Page Previous Next Advertisements ”;

Yii – AJAX Validation

Yii – AJAX Validation ”; Previous Next The username validation should only be done on the server side because only the server has the needed information. In this case, you can use AJAX-based validation. Step 1 − To enable the AJAX validation, modify the registration view this way. <?php use yiibootstrapActiveForm; use yiibootstrapHtml; ?> <div class = “row”> <div class = “col-lg-5″> <?php $form = ActiveForm::begin([”id” => ”registration-form”, ”enableAjaxValidation” => true]); ?> <?= $form->field($model, ”username”) ?> <?= $form->field($model, ”password”)->passwordInput() ?> <?= $form->field($model, ”email”)->input(”email”) ?> <?= $form->field($model, ”country”) ?> <?= $form->field($model, ”city”) ?> <?= $form->field($model, ”phone”) ?> <div class = “form-group”> <?= Html::submitButton(”Submit”, [”class” => ”btn btn-primary”, ”name” => ”registration-button”]) ?> </div> <?php ActiveForm::end(); ?> </div> </div> We should also prepare the server, so that it can handle the AJAX requests. Step 2 − Modify the actionRegistration method of the SiteController this way. public function actionRegistration() { $model = new RegistrationForm(); if (Yii::$app->request->isAjax && $model->load(Yii::$app->request>post())) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } return $this->render(”registration”, [”model” => $model]); } Step 3 − Now, go to http://localhost:8080/index.php?r=site/registration, you will notice that the form validation is done by AJAX requests. Print Page Previous Next Advertisements ”;

Yii – Creating Extensions

Yii – Creating Extensions ”; Previous Next Let us create a simple extension displaying a standard “Hello world” message. This extension will be distributed via the Packagist repository. Step 1 − Create a folder called hello-world in your hard drive but not inside the Yii basic application template). Inside the hello-world directory, create a file named composer.json with the following code. { “name”: “tutorialspoint/hello-world”, “authors”: [ { “name”: “tutorialspoint” } ], “require”: {}, “autoload”: { “psr-0”: { “HelloWorld”: “src/” } } } We have declared that we are using the PSR-0 standard and all extension files are under the src folder. Step 2 − Create the following directory path: hello-world/src/HelloWorld. Step 3 − Inside the HelloWorld folder, create a file called SayHello.php with the following code. <?php namespace HelloWorld; class SayHello { public static function world() { return ”Hello World, Composer!”; } } ?> We have defined a SayHello class with a world static function, which returns our hello message. Step 4 − The extension is ready. Now create an empty repository at your github account and push this extension there. Inside the hello-world folder run − git init git add git commit -m “initial commit” git remote add origin <YOUR_NEWLY_CREATED_REPOSITORY> git push -u origin master We have just sent our extension to the github. Now, go to the https://packagist.org, sign in and click “submit” at the top menu. You will see a page where you should enter your github repository to publish it. Step 5 − Click the “check” button and your extension is published. Step 6 − Go back to the basic application template. Add the extension to the composer.json. { “name”: “yiisoft/yii2-app-basic”, “description”: “Yii 2 Basic Project Template”, “keywords”: [“yii2”, “framework”, “basic”, “project template”], “homepage”: “http://www.yiiframework.com/”, “type”: “project”, “license”: “BSD-3-Clause”, “support”: { “issues”: “https://github.com/yiisoft/yii2/issues?state=open”, “forum”: “http://www.yiiframework.com/forum/”, “wiki”: “http://www.yiiframework.com/wiki/”, “irc”: “irc://irc.freenode.net/yii”, “source”: “https://github.com/yiisoft/yii2” }, “minimum-stability”: “dev”, “prefer-stable” : true, “require”: { “php”: “>=5.4.0”, “yiisoft/yii2”: “>=2.0.5”, “yiisoft/yii2-bootstrap”: “*”, “yiisoft/yii2-swiftmailer”: “*”, “kartik-v/yii2-widget-datetimepicker”: “*”, “tutorialspoint/hello-world”: “*” }, “require-dev”: { “yiisoft/yii2-codeception”: “*”, “yiisoft/yii2-debug”: “*”, “yiisoft/yii2-gii”: “*”, “yiisoft/yii2-faker”: “*” }, “config”: { “process-timeout”: 1800 }, “scripts”: { “post-create-project-cmd”: [ “yii\composer\Installer::postCreateProject” ] }, “extra”: { “yii\composer\Installer::postCreateProject”: { “setPermission”: [ { “runtime”: “0777”, “web/assets”: “0777”, “yii”: “0755” } ], “generateCookieValidationKey”: [ “config/web.php” ] }, “asset-installer-paths”: { “npm-asset-library”: “vendor/npm”, “bower-asset-library”: “vendor/bower” } } } Step 7 − Inside the project root folder, run the composer update to install/update all the dependencies. Step 8 − Our extension should be installed. To use it, modify the About view of the actionAbout method of the SiteController. <?php /* @var $this yiiwebView */ use yiihelpersHtml; $this->title = ”About”; $this->params[”breadcrumbs”][] = $this->title; $this->registerMetaTag([”name” => ”keywords”, ”content” => ”yii, developing, views, meta, tags”]); $this->registerMetaTag([”name” => ”description”, ”content” => ”This is the description of this page!”], ”description”); ?> <div class = “site-about”> <h1><?= Html::encode($this->title) ?></h1> <p> This is the About page. You may modify the following file to customize its content: </p> <h1><?= HelloWorldSayHello::world(); ?></h1> </div> Step 9 − Type http://localhost:8080/index.php?r=site/about in the web browser. You will see a hello world message from our extension. Print Page Previous Next Advertisements ”;