Friday 6 January 2017

YII Frame Work Structures

Yii Structure

Yii2 has a new and improved application structure. It uses composer to manage its dependencies. Yii1 has only a basic application structure. While Yii2 has basic as well as advanced application structure.
Yii2 divides the entire application into following sections:
  • Backend : For backend web development
  • Common : Include common files for all the application
  • Console : Console application
  • Environments : Environment configurations
  • Frontend : For frontend web development

Yii2 Directory Structure

  1. ROOT  
  2.     /                   contains the frontend entry script and web resources  
  3.     /assets             contains the frontend web assets  
  4. common  
  5.     config/             contains shared configurations  
  6.     mail/               contains view files for e-mails  
  7.     models/             contains model classes used in both backend and frontend  
  8.     tests/              contains various tests for objects that are common among applications  
  9. console  
  10.     config/             contains console configurations  
  11.     controllers/        contains console controllers (commands)  
  12.     migrations/         contains database migrations  
  13.     models/             contains console-specific model classes  
  14.     runtime/            contains files generated during runtime  
  15.     tests/              contains various tests for the console application  
  16. backend  
  17.     assets/             contains application assets such as JavaScript and CSS  
  18.     config/             contains backend configurations  
  19.     controllers/        contains Web controller classes  
  20.     models/             contains backend-specific model classes  
  21.     runtime/            contains files generated during runtime  
  22.     tests/              contains various tests for the backend application  
  23.     views/              contains view files for the Web application  
  24.     web/                contains the entry script and Web resources  
  25. frontend  
  26.     assets/             contains application assets such as JavaScript and CSS  
  27.     config/             contains frontend configurations  
  28.     controllers/        contains Web controller classes  
  29.     models/             contains frontend-specific model classes  
  30.     runtime/            contains files generated during runtime  
  31.     tests/              contains various tests for the frontend application  
  32.     views/              contains view files for the Web application  
  33. vendor/                 contains dependent 3rd-party packages  
  34. environments/           contains environment-based overrides  

assets

Asset bundles are used to include JavaScript and style sheets. Lot of assessment and caching is done through the assets.
There is one more asset folder inside the web directory. Yii uses this folder to cache the assets. It will have a .gitignore in this folder.
If JavaScript or CSS files are need to be updated, all the folders in this directory need to be deleted. They can be deleted any time and can be auto-generated by Yii as cache files.

commands

This directory allows you to create Yii management scripts to run. These commands can be executed on command line by going on Yii root directory and typing php yii or ./yii. It will display a by default available commands list .

config

The config folder includes configuration settings which include e-mail sending, database connection, etc.

controllers

Controllers manage data traffic in MVC framework. When request is made, it is controller that processes that request.

mail

It stores templates that Yii uses to construct a mail.

models

Models manage all the database work in MVC. Any type of coding related to database is written in model.

runtime

This folder is used during processing of a web requests.

tests

This folder checks the functionality.

vendor

Yii source files reside in this directory. Third party installed module will be stored here. During upgradation, codes in this folder are overwritten hence code alteration in this directory should be avoided.

views

Views in MVC contains the pages which are displayed upon a web request. All the HTML coding is done in view directory.

web

This is the document root directory that the web server points to. The index.php file launches the Yii process when called. In this file, debugging code can be turned on or off. Debug bar is viewable at the bottom of the page.
Here you can put any files, images or anything else which needs web accessibility. Files placed in this folder only will be accessed.
Inside this web directory a subdirectory named asset is also present. This directory is used to respond web requests.

Yii Entry Scripts

It is the first step in application handling process and responsible to start a request handling cycle. An application has a single entry script. Request made by end users comes to entry script which initialize the application and forward the request to them.
These scripts are stored under web application directories to make them accessible by the end users. By default, they are named as index.php but can also be given other names.
For a console application, entry scripts are stored in base path and named as yii.php. They should be made executable for users to run on console application.
Entry scripts perform following work:
  • Define global constants
  • Register Composer autoloader
  • Include Yii class file
  • Load application configuration
  • Create and configure an application instance
  • Call the application to process the request

Defining Constants

Global constants are very well defined in the entry scripts. They should be defined at the beginning of an entry script for effective result when other PHP files are included. Yii framework supports following three constants:
  • YII_DEBUG: It specifies whether an application is running in debug mode or not. This mode should be mainly used during development. Because an application will keep more log information and will reveal detailed error if in debug mode.
  • YII_ENV: It defines the environment the application is running in. Its default value is 'prod' which stands for 'Production'. Other values are dev and test.
  • YII_ENABLE_ERROR_HANDLER: By default it is always true. It specifies whether to enable or disable the error handler value.

Yii Models

Models are part of MVC structure. They represent the rules and logic for an application. Means they hold data and define the validating rules for the data.
Model classes are extended by yii\base\Model or its child classes.
Mainly following features are implemented using models.
  • attribute declaration
  • attribute labels
  • massive attribute assignment
  • scenario-based validation
  • can not embed HTML
  • can not be directly accessed

Attributes

Attributes mainly represent the business data. Each attribute is a publicly accessible property of a model. They can be accessed like array elements or normal object properties. it is like publicly accessible properties of a model.
The method,
  1. yii\base\Model::attributes()   
specifies what attributes a model class has.
Model class is also the base class for ActiveRecord class (which is an advanced model with additional functionality).
Attribute as a normal object property:
  1. $model = new \app\models\ContactForm;  
  2.   
  3. // "name" is an attribute of ContactForm  
  4. $model->name = 'example';  
  5. echo $model->name;  
  6.   
  7. Attribute as array elements:  
  8.   
  9. $model = new \app\models\ContactForm;  
  10.   
  11. // accessing attributes like array elements  
  12. $model['name'] = 'example';  
  13. echo $model['name'];  
  14.   
  15. // Model is traversable using foreach.  
  16. foreach ($model as $name => $value) {  
  17.     echo "$name: $value\n";  
  18. }  
In earlier versions of Yii, scenarios and validation were handled with the same function. But in Yii2, they are split into different functions i.e; rules() and scenarios().
Here, rules() specify the validation of a data while scenarios() specify which attributes are safe to be assigned to the model.

Attribute Labels

Attribute labels are values which are displayed with attributes to get the input from the users.
For example, in the below code, ID, Name, Designation, Contact and Email denotes the attribute labels. All this is defined under a function attributeLabels().
  1. public function attributeLabels()   
  2.     {   
  3.         return [   
  4.             'id' => 'ID',   
  5.             'name' => 'Name',   
  6.             'designation' => 'Designation',   
  7.             'contact' => 'Contact',   
  8.             'email' => 'Email',   
  9.         ];   
  10.     }  
YII Models 1
Look at the above snapshot, the heading data denotes the attribute labels.

Scenarios

A model may be used for different scenarios. For example, a model may be used to collect login user inputs while it may also be used to collect inputs of new users for registration. So in different scenarios a model may use different rules and logic.
Example
This is the ContactForm.php code,
  1. <?php   
  2.    namespace frontend\models;   
  3.    use Yii;   
  4.    use yii\base\Model;   
  5.    /**  
  6.    * ContactForm is the model behind the contact form.  
  7.    */   
  8.    class ContactForm extends Model {   
  9.       public $name;   
  10.       public $email;   
  11.       public $subject;   
  12.       public $body;   
  13.       public $verifyCode;   
  14.        const SCENARIO_EMAIL_FROM_GUEST = 'EMAIL_FROM_GUEST';   
  15.       const SCENARIO_EMAIL_FROM_USER = 'EMAIL_FROM_USER';   
  16.        
  17.       public function scenarios() {   
  18.          return [   
  19.             self::SCENARIO_EMAIL_FROM_GUEST => ['name''email''subject',   
  20.                'body''verifyCode'],   
  21.             self::SCENARIO_EMAIL_FROM_USER => ['name''email' ,'subject''body',   
  22.                'verifyCode'],   
  23.          ];   
  24.       }   
  25.       /**  
  26.       * @return array the validation rules.  
  27.       */   
  28.       public function rules() {   
  29.          return [   
  30.             // name, email, subject and body are required   
  31.             [['name''email''subject''body'], 'required'],   
  32.             // email has to be a valid email address   
  33.             ['email''email'],   
  34.             // verifyCode needs to be entered correctly   
  35.             ['verifyCode''captcha'],   
  36.          ];   
  37.       }   
  38.       /**  
  39.       * @return array customized attribute labels  
  40.       */   
  41.       public function attributeLabels() {   
  42.          return [   
  43.            'name' => 'Name',   
  44.             'email' => 'Email',   
  45.             'subject' => 'Subject',   
  46.             'body' => 'Body',   
  47.             'verifyCode' => 'Verification Code',   
  48.          ];   
  49.       }   
  50.       /**  
  51.       * Sends an email to the specified email address using the information  
  52.          collected by this model.  
  53.       * @param  string  $email the target email address  
  54.       * @return boolean whether the model passes validation  
  55.       */   
  56.       public function contact($email) {   
  57.          if ($this -> validate()) {   
  58.             Yii::$app->mailer->compose()   
  59.                ->setTo($email)   
  60.                ->setFrom([$this->email => $this->name])   
  61.                ->setSubject($this->subject)   
  62.                ->setTextBody($this->body)   
  63.                ->send();   
  64.             return true;   
  65.          }   
  66.          return false;   
  67.       }   
  68.    }   
  69. ?>  
Create an action actionContact in SiteController.php file
  1. public function actionContact() {   
  2.  $model = new ContactForm();   
  3.  $model->scenario = ContactForm::SCENARIO_EMAIL_FROM_GUEST;   
  4.  if ($model->load(Yii::$app->request->post()) && $model->   
  5.     contact(Yii::$app->params ['adminEmail'])) {   
  6.        Yii::$app->session->setFlash('contactFormSubmitted');    
  7.        return $this->refresh();   
  8.  }   
  9.  return $this->render('contact', [   
  10.     'model' => $model,   
  11.  ]);   
Now, we'll run the program in the browser,
YII Models 2
Now change the scenarion in actionContact in SiteController.php as
  1. $model->scenario = ContactForm::SCENARIO_EMAIL_FROM_USER;  
Now on running the program in the browser, Subject and Body field will be no longer required field.
YII Models 3

Validation Rules

These are the rules which are set for the fields to be fulfilled by the users. For example, required rule will make sure that the respective field is not empty. And email attribute will make sure that the email entered is a valid email. If values do not satisfy the rules, an error message will appear on the screen.
To declare validation rules for all the fields in all the scenarios, following code is used.
  1. public function rules()  
  2. {  
  3.     return [  
  4.         // the name, email, subject and body attributes are required  
  5.         [['name''email''subject''body'], 'required'],  
  6.   
  7.         // the email attribute should be a valid email address  
  8.         ['email''email'],  
  9.     ];  
  10. }  
  11.   
  12. To declare different validation rules for different scenarios, use the following code.  
  13.   
  14. public function rules()  
  15. {  
  16.     return [  
  17.         // username, email and password are all required in "register" scenario  
  18.         [['username''email''password''d_o_b'], 'required''on' => self::SCENARIO_REGISTER],  
  19.   
  20.         // username and password are required in "login" scenario  
  21.         [['username''password'], 'required''on' => self::SCENARIO_LOGIN],  
  22.     ];  
  23. }  
The on property implements that, rule will be applied to a particular scenario. If you'll not use on property than by default rule will be applied for all the fields.

Massive Assignment

In massive assignment, a model is populated with user inputs using a single line of code. Massive assignment only applies to the safe attributes.
Look at the following two types of code, both assigning the submitted form data by the end users to attributes of the ContactForm model.
First one is,
  1. $model = new \app\models\ContactForm;  
  2. $model->attributes = \Yii::$app->request->post('ContactForm');  
  3. Second one is,  
  4.   
  5.   
  6. $model = new \app\models\ContactForm;  
  7. $data = \Yii::$app->request->post('ContactForm', []);  
  8. $model->name = isset($data['name']) ? $data['name'] : null;  
  9. $model->email = isset($data['email']) ? $data['email'] : null;  
  10. $model->subject = isset($data['subject']) ? $data['subject'] : null;  
  11. $model->body = isset($data['body']) ? $data['body'] : null;  
The first one using massive assignment is much easier, neat and less error prone.

Views

View part in the MVC structure is responsible to present data in front of users. They mainly contain the HTML content and presentational PHP code.

Creating Views

Look at the About page code of basic Yii page.
  1. <?php   
  2.   
  3. /* @var $this yii\web\View */   
  4.   
  5. use yii\helpers\Html;   
  6.   
  7. $this->title = 'About';   
  8. $this->params['breadcrumbs'][] = $this->title;   
  9. ?>   
  10. <div class="site-about">   
  11.     <h1><?= Html::encode($this->title) ?></h1>   
  12.   
  13.     <p>This is the About page. You may modify the following file to customize its content:</p>   
  14.   
  15.     <code><?= __FILE__ ?></code>   
  16. </div>   
And it's output is this:
YII Views 1
In the above script, PHP code is used to generate the dynamic content in title and inside the form tag. HTML tags displays the data in a presentation view.

View Conventions

  • Views rendered by a controller should be written into @app/views/controllerID folder.
  • Views rendered by a widget should be written into widgetPath/views folder.
Following controller methods can be called to render views within controller:
  • render() : Renders the mentioned view file and applies a layout.
  • renderPartial() : Renders the mentioned view but without applying a layout.
  • renderAjax() : Renders a view without a layout and injects all registered JS scripts and CSS files.
  • renderFile() : Renders a view file in the specified path.
  • renderContent() : Renders a static ring.
Following controller methods can be called to render views within another view:
  • render() : Renders a view page.
  • renderAjax() : Renders a view without a layout and injects all registered JS scripts and CSS files.
  • renderFile() : Renders a view file in the specified path.
Following controller methods can be called to render views within widgets:
  • render() : Renders a view page.
  • renderFile() : Renders a view file in the specified path.
Example:
Step 1 Inside views/site folder, we are creating a view file exm.php file.
  1. <!DOCTYPE html>   
  2. <html>   
  3. <head>   
  4.     <title></title>   
  5. </head>   
  6. <body>   
  7.     <h1>Hello, welcome to JavaTpoint.</h1>   
  8. </body>   
  9. </html>  
Step 2 Render exm.php view file in the about.php view file in the site folder.
  1. <?php   
  2.   
  3. /* @var $this yii\web\View */   
  4.   
  5. use yii\helpers\Html;   
  6.   
  7. $this->title = 'About';   
  8. $this->params['breadcrumbs'][] = $this->title;   
  9. ?>   
  10. <div class="site-about">   
  11.     <h1><?= Html::encode($this->title) ?></h1>   
  12.   
  13.     <p>This is the About page. You may modify the following file to customize its content:</p>   
  14.   
  15.      <?= $this->render("exm") ?>   
  16.   
  17.     <code><?= __FILE__ ?></code>   
  18. </div>   
Step 3 Run it on the browser.
YII Views 2

Controllers

In MVC structure, controllers role is to process the requests from the user and generate the responses. The incoming requests are analyzed by the controllers, passed onto models, models results are directed into views and finally a response is generated.

Controllers Action

Controller contains actions which are called by user to execute a request. A controller can have more than one request.
Following code is an example with two actions update and create in a controller file SiteController.php.
  1. <?php   
  2.   
  3. namespace frontend\controllers;   
  4.   
  5. use Yii;   
  6. use frontend\models\Yiicrud;   
  7. use frontend\models\SearchYiicrud;   
  8. use yii\web\Controller;   
  9. use yii\web\NotFoundHttpException;   
  10. use yii\filters\VerbFilter;   
  11.   
  12. /**  
  13.  * YiicrudController implements the CRUD actions for Yiicrud model.  
  14.  */   
  15. class YiicrudController extends Controller   
  16. {   
  17.     /**  
  18.      * @inheritdoc  
  19.      */   
  20.     public function behaviors()   
  21.     {   
  22.         return [   
  23.             'verbs' => [   
  24.                 'class' => VerbFilter::className(),   
  25.                 'actions' => [   
  26.                     'delete' => ['POST'],   
  27.                 ],   
  28.             ],   
  29.         ];   
  30.     }  
  31. public function actionUpdate($id)   
  32.     {   
  33.         $model = $this->findModel($id);   
  34.   
  35.         if ($model->load(Yii::$app->request->post()) && $model->save()) {   
  36.             return $this->redirect(['view''id' => $model->id]);   
  37.         } else {   
  38.            return $this->render('update', [   
  39.                 'model' => $model,   
  40.             ]);   
  41.         }   
  42.     }   
  43.   
  44.     /**  
  45.      * Deletes an existing Yiicrud model.  
  46.      * If deletion is successful, the browser will be redirected to the 'index' page.  
  47.      * @param integer $id  
  48.      * @return mixed  
  49.      */   
  50.     public function actionDelete($id)   
  51.     {   
  52.         $this->findModel($id)->delete();   
  53.   
  54.         return $this->redirect(['index']);   
  55.     }  
Look at the above code, action update (actionUpdate( )), it will first load the model according to requested id, then tries to include the new model instance using the request data and save the model. Then it will be redirected to view action with the model id. Otherwise, it will return the update action.
Action delete (actionDelete( )), it will load the model according to requested id,and then delete it. It will be redirected to the index action.
Routes
In Yii URL, you must have noticed there is a r. This r is the route.
For example: http://localhost/index.php?r=site/index
The route is site/index in the above example.
which consist of the following parts:
moduleID : It applies only when controller belongs to a non-application module.
controllerID : A string that identifies the controller among all controllers within a same module. In above example, it is site.
actionID : A string that identifies the action name among all actions in a controller. In above example, it is index.
Route format is:
ControllerID/ActionID
If belongs to a module, it takes the following format:
  1. ModuleID/ControllerID/ActionID  


Controllers Action

Actions are defined in the controllers file. They need to be called while executing a request in an application through the URL.

Creating Action

An action is created by defining a public method whose name starts with the word action.
Example:
Step 1 We'll create an action named index2 in the SampleController.php file.
  1. <?php   
  2. namespace frontend\controllers;   
  3.   
  4. use Yii;   
  5. use yii\web\Controller;   
  6.   
  7. class SampleController extends Controller   
  8. {   
  9.     public function actionIndex()   
  10.     {   
  11.       return $this->render('index');   
  12.     }   
  13.       
  14.     public function actionIndex2()   
  15.     {   
  16.          return "<h1>This action is Index2</h2>";   
  17.     }   
  18. }   
  19. ?>  
Step 2 Run it on the browser.
http://localhost/action/frontend/web/index.php?r=sample/index2
YII Controllers action 1

Action IDs

An action is created to perform a particular request, and hence it is generally named as verbs like create, view, update, delete, etc.
An action ID can contain only these letters:
  • English letters in lower case
  • Underscores
  • Hyphens
  • Numbers after english alphabets like index2 in the above example.
Actions can be created in two ways:
  • Inline action
  • Standalone action

Inline Action

Inline action is a method in the controller class. These are the most commonly created actions when they don't need to be used more than once and are easy to create.
Inline action ID name is defined according to the following points:
  • Start the method name with the action prefix.
  • The first letter of the word after action will be in upper case.
  • Remove hyphens.
For example,
  • Index2 becomes actionIndex2
  • login-form becomes actionLoginForm

Standalone Action

A standalone action extends yii\base\Action or its child classes. These actions are mainly created when they need to be used in different controllers or redistributes as extensions.
They can be defined as separate classes and then connect them to your controllers. This way they will be able to reuse.
These actions must implement a method called run() and extend to yii\base\Action or a child class.
Example
We'll demonstrate a simple use of standalone action.
Step 1 Create a folder standing in the frontend directory of your Yii2 folder.
Step 2 Now create a MultiAction.php file in above created folder.
  1. <?php   
  2.    namespace frontend\standing;   
  3.    use yii\base\Action;   
  4.    class MultiAction extends Action {   
  5.       public function run() {   
  6.          return "<h3>This is StandAlone action example</h3>";   
  7.       }   
  8.    }   
  9. ?>  
Look at the above code, we have created a standalone action named as MultiAction which extends to Action class. The have implemented the run() method.
Step 3 In the above created SampleController.php file add some extra codes.
  1. <?php   
  2. namespace frontend\controllers;   
  3.   
  4. use Yii;   
  5. use yii\web\Controller;   
  6.   
  7. class SampleController extends Controller   
  8. {   
  9.      
  10.     public function actionIndex()   
  11.     {   
  12.       return $this->render('index');   
  13.     }   
  14.       
  15.      public function actions()  
  16.      {   
  17.          return [   
  18.             'multi' => 'frontend\standing\MultiAction',   
  19.          ];   
  20.       }   
  21.   
  22.   
  23.     public function actionIndex2()   
  24.     {   
  25.          return "<h1>This action is Index2</h2>";   
  26.     }   
  27. }   
  28. ?>  
Look at the above code, actions() method returns the standalone action which is multi action created in the standing folder.
Step 4 Run it on the browser with the URL,
http://localhost/action/frontend/web/index.php?r=sample/multi
YII Controllers action 2

Action Return Value

Return value of an action stands for the result of the corresponding action.
The following example shows an action being redirected to a new URL by returning a response object. The redirect() method always returns a response object.
Step1 Add the following code in the SampleController.php file.
  1. public function actionMysite()   
  2. {   
  3.     // redirect the user browser to http://example.com   
  4.     return $this->redirect('http://javatpoint.com');   
  5. }  
Step 2 Run it on the browser with the following URL,
http://localhost/action/frontend/web/index.php?r=sample/mysite
The above URL will result the javatpoint.com site in front of you.

Action Parameters

You can also add parameters to the action methods. Their values will be retrieved from the $_GET method using parameter name as key.
Step 1 Add the following code in the SampleController.php file.
  1. public function actionPara($a$b)   
  2.     {   
  3.         return "$a $b";   
  4.     }   
Step 2 Run it on the browser with the following URL,
http://localhost/action/frontend/web/index.php?r=sample/para&a=Welcome to&b=our site
YII Controllers action 3
In the above URL, if you'll not provide any value to a and b variables, exception error will be thrown.

Default Action

A default action is always specified in every controllers file. By default, it is set as index.
When in the route, URL only contains controller ID, then it goes to default action that is index. However this default value can be changed by overriding it.
namespace app\controllers;
use yii\web\Controller;
  1. class SiteController extends Controller  
  2. {  
  3.     public $defaultAction = 'main_page';  
  4.   
  5.     public function actionHome()  
  6.     {  
  7.         return $this->render('main_page');  
  8.     }  
  9. }  




Modules

A module resides in the main application and organized as a directory that is called base path of the module. This module directory will have its own MVC (model, view and controller) and other supporting components just like an application.

Module Structure

Modules follow a typical structure as shown below.
  1. newModule/  
  2.     Module.php                   the module class file  
  3.     controllers/                 containing controller class files  
  4.         DefaultController.php    the default controller class file  
  5.     models/                      containing model class files  
  6.     views/                       containing controller view and layout files  
  7.         layouts/                 containing layout view files  
  8.         default/                 containing view files for DefaultController  
  9.             index.php            the index view file  

Module Class

Module class characteristics:
  • Each module should have a unique class extending to yii\base\Module.
  • Class should be located under module's base path and should be accessible.
  • On execution, a single instance of the module class will be created.
  • Module instances are used to share data and components for codes within modules.
  • By default it is named as Module.php.
Example
Let's look at an example to create a module.
Step 1 Create modules named folder in Frontend directory of your Yii2 folder.
Step 2 Inside modules folder create a folder named as project.
Step 3 Inside project folder create a file named as Project.php.
  1. <?php   
  2.   
  3. namespace frontend\modules\project;   
  4.   
  5. /**  
  6.  * project module definition class  
  7.  */   
  8. class Project extends \yii\base\Module   
  9. {   
  10.     /**  
  11.      * @inheritdoc  
  12.      */   
  13.     public $controllerNamespace = 'frontend\modules\project\controllers';   
  14.   
  15.     /**  
  16.      * @inheritdoc  
  17.      */   
  18.     public function init()   
  19.     {   
  20.         parent::init();   
  21.   
  22.         // custom initialization code goes here   
  23.     }   
  24. }   
Look at the above code, this is module class we have created. The init() function here is to initialize the module's properties.
Step 4 Inside project folder create two more folders named as controllers and views.
Step 5 Inside controllers folder create EmpController.php file.
  1. <?php   
  2.   
  3. namespace frontend\modules\project\controllers;   
  4.   
  5. use yii\web\Controller;   
  6.   
  7. /**  
  8.  * Default controller for the `project` module  
  9.  */   
  10. class EmpController extends Controller   
  11. {   
  12.     /**  
  13.      * Renders the index view for the module  
  14.      * @return string  
  15.      */   
  16.     public function actionMessage()   
  17.     {   
  18.         return $this->render('message');   
  19.     }   
  20. }   
Look at the above snapshot, here we have defined the action actionMessage.
Step 6 Inside views folder create emp folder and inside it create message.php file.
<h1>This is an Example to create a Module.</h1>
The below snapshot shows our final modules's structure in our modd directory. It displays all the files created inside modd/frontend/modules directory.
YII Moudles 1
Step 7 Now we need to do some config settings to add our module. Go to config folder of frontend directory.
Add the module in the file main.php in the config folder.
  1. <?php   
  2. $params = array_merge(   
  3.     require(__DIR__ . '/../../common/config/params.php'),   
  4.     require(__DIR__ . '/../../common/config/params-local.php'),   
  5.     require(__DIR__ . '/params.php'),   
  6.     require(__DIR__ . '/params-local.php')   
  7. );   
  8.   
  9. return [   
  10.     'id' => 'app-frontend',   
  11.     'basePath' => dirname(__DIR__),   
  12.     'bootstrap' => ['log'],   
  13.     'controllerNamespace' => 'frontend\controllers',   
  14.      'modules' => [   
  15.         'project' =>[   
  16.             'class' => 'frontend\modules\project\Project',   
  17.        ],   
  18.     ],   
  19.     'components' => [   
  20.         'request' => [   
  21.             'csrfParam' => '_csrf-frontend',   
  22.         ],   
  23.         'user' => [   
  24.             'identityClass' => 'common\models\User',   
  25.             'enableAutoLogin' => true,   
  26.             'identityCookie' => ['name' => '_identity-frontend''httpOnly' => true],   
  27.         ],   
  28.         'session' => [   
  29.             // this is the name of the session cookie used for login on the frontend   
  30.             'name' => 'advanced-frontend',   
  31.         ],   
  32.         'log' => [   
  33.             'traceLevel' => YII_DEBUG ? 3 : 0,   
  34.             'targets' => [   
  35.                 [   
  36.                     'class' => 'yii\log\FileTarget',   
  37.                     'levels' => ['error''warning'],   
  38.                 ],   
  39.             ],   
  40.         ],   
  41.         'errorHandler' => [   
  42.             'errorAction' => 'site/error',   
  43.         ],   
  44.         /*  
  45.         'urlManager' => [  
  46.             'enablePrettyUrl' => true,  
  47.             'showScriptName' => false,  
  48.             'rules' => [  
  49.             ],  
  50.         ],  
  51.         */   
  52.     ],   
  53.     'params' => $params,   
  54. ];   
Step 8 Run it on the browser with the following URL,
http://localhost/modd/frontend/web/index.php?r=project/emp/message
YII Moudles 2

Important Points:

  • Modules should be used for large applications. Divide its features into several groups and develop them as a module.
  • Modules should be reusable for the future projects.






Widgets

Widgets are reusable building blocks on client-side (containing JavaScript, HTML and CSS). They are used to create complex and configurable user interface elements in views.
For example, a Progress widget and DatePicker widget can create a progress bar and stylist date picker in your application.

Using Widgets

Widgets are majorly used in views. To call a widget you can call,
  1. yii\base\Widget::widget()  
This method takes a configuration array for initializing the widget.
For example, the following code inserts a date picker widget configured to use Russian language.
  1. <?php  
  2. use yii\jui\DatePicker;  
  3. ?>  
  4. <?= DatePicker::widget([  
  5.     'model' => $model,  
  6.     'attribute' => 'from_date',  
  7.     'language' => 'ru',  
  8.     'clientOptions' => [  
  9.         'dateFormat' => 'yy-mm-dd',  
  10.     ],  
  11. ])   
  12. ?>  
Example
In this example, we'll use progress widget.
Step 1 Create an action actionWidget() in the SiteController.php file in the frontend directory.
  1. public function actionWidget()   
  2.     {   
  3.    return $this->render('widget');   
  4.     }  
Look at the above code, we are rendering to the widget page in view folder.
Step 2 Create a page widget.php in the views/site folder in the frontend directory.
  1. <?php   
  2.    use yii\bootstrap\Progress;   
  3. ?>   
  4. <?= Progress::widget(['percent' => 99, 'label' => 'Loading 99%']) ?>  
Step 3 Run it on the browser with the URL,
http://localhost/wid/frontend/web/index.php?r=site/widget

No comments:

Post a Comment