Yii – Extensions ”; Previous Next Extensions are packages specifically designed to be used in Yii applications. You can share your own code as an extension or use third-party extensions to add features to your application. Using Extensions Most extensions are distributed as Composer packages. Composer installs packages from Packagist – the repository for Composer packages. To install a third-party extension, you should − Add the extension to a composer.json file. Run composer install. Adding Date and Time Widget Let us add a neat datetime widget to our project. Step 1 − Modify the composer.json file of the basic application template this way. { “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”: “stable”, “require”: { “php”: “>=5.4.0”, “yiisoft/yii2”: “>=2.0.5”, “yiisoft/yii2-bootstrap”: “*”, “yiisoft/yii2-swiftmailer”: “*”, “kartik-v/yii2-widget-datetimepicker”: “*” }, “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” } } } We have added the dependency “kartik-v/yii2-widget-datetimepicker”: “*” to the required section. Step 2 − Now, inside the project root, run the composer update to update all the dependencies. We have just installed the extension. You will find it inside the vendor/kartik-v/yii2widget-datetimepicker folder. Step 3 − To display the newly installed widget in the page, modify the About view of the actionAbout method of the SiteController. <?php /* @var $this yiiwebView */ use kartikdatetimeDateTimePicker; 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> <?php echo DateTimePicker::widget([ ”name” => ”dp_1”, ”type” => DateTimePicker::TYPE_INPUT, ”value” => ”23-Feb-1982 10:10”, ”pluginOptions” => [ ”autoclose”=>true, ”format” => ”dd-M-yyyy hh:ii” ] ]); ?> </div> Step 4 − Now, run the built-in php server from the project root via the php -S localhost:8080t web command. Step 5 − Go to http://localhost:8080/index.php?r=site/about. You will see a neat datetime picker as shown in the following screenshot. Print Page Previous Next Advertisements ”;
Category: yii
Yii – Models
Yii – Models ”; Previous Next Models are objects representing business logic and rules. To create a model, you should extend the yiibaseModel class or its subclasses. Attributes Attributes represent the business data. They can be accessed like array elements or object properties. Each attribute is a publicly accessible property of a model. To specify what attributes a model possesses, you should override the yiibaseModel::attributes() method. Let us have a look at the ContactForm model of the basic application template. <?php namespace appmodels; use Yii; use yiibaseModel; /** * ContactForm is the model behind the contact form. */ class ContactForm extends Model { public $name; public $email; public $subject; public $body; public $verifyCode; /** * @return array the validation rules. */ public function rules() { return [ // name, email, subject and body are required [[”name”, ”email”, ”subject”, ”body”], ”required”], // email has to be a valid email address [”email”, ”email”], // verifyCode needs to be entered correctly [”verifyCode”, ”captcha”], ]; } /** * @return array customized attribute labels */ public function attributeLabels() { return [ ”verifyCode” => ”Verification Code”, ]; } /** * Sends an email to the specified email address using the information collected by this model. * @param string $email the target email address * @return boolean whether the model passes validation */ public function contact($email) { if ($this->validate()) { Yii::$app->mailer->compose() ->setTo($email) ->setFrom([$this->email => $this->name]) ->setSubject($this->subject) ->setTextBody($this->body) ->send(); return true; } return false; } } ?> Step 1 − Create a function called actionShowContactModel in the SiteController with the following code. public function actionShowContactModel() { $mContactForm = new appmodelsContactForm(); $mContactForm->name = “contactForm”; $mContactForm->email = “[email protected]”; $mContactForm->subject = “subject”; $mContactForm->body = “body”; var_dump($mContactForm); } In the above code, we define the ContactForm model, set attributes, and display the model on the screen. Step 2 − Now, if you type http://localhost:8080/index.php?r=site/show-contact-model in the address bar of the web browser, you will see the following. If your model extends from yiibaseModel, then all its member variables (public and non-static) are attributes. There are five attributes in the ContactForm model − name, email, subject, body, verifyCode and you can easily add new ones. Attribute Labels You often need to display labels associated with attributes. By default, attribute labels are automatically generated by the yiibaseModel::generateAttributeLabel() method. To manually declare attribute labels, you may override the yiibaseModel::attributeLabels() method. Step 1 − If you open http://localhost:8080/index.php?r=site/contact, you will see the following page. Note that the attribute labels are the same as their names. Step 2 − Now, modify the attributeLabels function in the ContactForm model in the following way. public function attributeLabels() { return [ ”name” => ”name overridden”, ”email” => ”email overridden”, ”subject” => ”subject overridden”, ”body” => ”body overridden”, ”verifyCode” => ”verifyCode overridden”, ]; } Step 3 − If you open http://localhost:8080/index.php?r=site/contact again, you will notice that the labels have changed as shown in the following image. Scenarios You can use a model in different scenarios. For example, when a guest wants to send a contact form, we need all the model attributes. When a user wants to do the same thing, he is already logged in, so we do not need his name, as we can easily take it from the DB. To declare scenarios, we should override the scenarios() function. It returns an array whose keys are the scenario names and values are active attributes. Active attributes are the ones to validate. They can also be massively assigned. Step 1 − Modify the ContactForm model in the following way. <?php namespace appmodels; use Yii; use yiibaseModel; /** * ContactForm is the model behind the contact form. */ class ContactForm extends Model { public $name; public $email; public $subject; public $body; public $verifyCode; const SCENARIO_EMAIL_FROM_GUEST = ”EMAIL_FROM_GUEST”; const SCENARIO_EMAIL_FROM_USER = ”EMAIL_FROM_USER”; public function scenarios() { return [ self::SCENARIO_EMAIL_FROM_GUEST => [”name”, ”email”, ”subject”, ”body”, ”verifyCode”], self::SCENARIO_EMAIL_FROM_USER => [”email” ,”subject”, ”body”, ”verifyCode”], ]; } /** * @return array the validation rules. */ public function rules() { return [ // name, email, subject and body are required [[”name”, ”email”, ”subject”, ”body”], ”required”], // email has to be a valid email address [”email”, ”email”], // verifyCode needs to be entered correctly [”verifyCode”, ”captcha”], ]; } /** * @return array customized attribute labels */ public function attributeLabels() { return [ ”name” => ”name overridden”, ”email” => ”email overridden”, ”subject” => ”subject overridden”, ”body” => ”body overridden”, ”verifyCode” => ”verifyCode overridden”, ]; } /** * Sends an email to the specified email address using the information collected by this model. * @param string $email the target email address * @return boolean whether the model passes validation */ public function contact($email) { if ($this -> validate()) { Yii::$app->mailer->compose() ->setTo($email) ->setFrom([$this->email => $this->name]) ->setSubject($this->subject) ->setTextBody($this->body) ->send(); return true; } return false; } } ?> We have added two scenarios. One for the guest and another for authenticated user. When the user is authenticated, we do not need his name. Step 2 − Now, modify the actionContact function of the SiteController. public function actionContact() { $model = new ContactForm(); $model->scenario = ContactForm::SCENARIO_EMAIL_FROM_GUEST; if ($model->load(Yii::$app->request->post()) && $model-> contact(Yii::$app->params [”adminEmail”])) { Yii::$app->session->setFlash(”contactFormSubmitted”); return $this->refresh(); } return $this->render(”contact”, [ ”model” => $model, ]); } Step 3 − Type http://localhost:8080/index.php?r=site/contact in the web browser. You will notice that currently, all model attributes are required. Step 4 − If you change the scenario of the model in the actionContact, as given in the following code, you will find that the name attribute is no longer required. $model->scenario = ContactForm::SCENARIO_EMAIL_FROM_USER; Massive Assignment Massive assignment is a convenient way of creating a model from multiple input attributes via a single line of code. The lines of code are − $mContactForm = new appmodelsContactForm; $mContactForm->attributes = Yii::$app->request->post(”ContactForm”); The above given lines of code are equivalent to − $mContactForm = new appmodelsContactForm; $postData = Yii::$app->request->post(”ContactForm”, []); $mContactForm->name = isset($postData[”name”]) ? $postData[”name”] : null; $mContactForm->email = isset($postData[”email”]) ? $postData[”email”] : null; $mContactForm->subject = isset($postData[”subject”]) ? $postData[”subject”] : null; $mContactForm->body = isset($postData[”body”]) ? $postData[”body”] : null; The former is much cleaner. Notice that massive assignment only applies
Yii – Controllers
Yii – Controllers ”; Previous Next Controllers are responsible for processing requests and generating responses. After user”s request, the controller will analyze request data, pass them to model, then insert the model result into a view, and generate a response. Understanding Actions Controllers include actions. They are the basic units that user can request for execution. A controller can have one or several actions. Let us have a look at the SiteController of the basic application template − <?php namespace appcontrollers; use Yii; use yiifiltersAccessControl; use yiiwebController; use yiifiltersVerbFilter; use appmodelsLoginForm; use appmodelsContactForm; class SiteController extends Controller { public function behaviors() { return [ ”access” => [ ”class” => AccessControl::className(), ”only” => [”logout”], ”rules” => [ [ ”actions” => [”logout”], ”allow” => true, ”roles” => [”@”], ], ], ], ”verbs” => [ ”class” => VerbFilter::className(), ”actions” => [ ”logout” => [”post”], ], ], ]; } public function actions() { return [ ”error” => [ ”class” => ”yiiwebErrorAction”, ], ”captcha” => [ ”class” => ”yiicaptchaCaptchaAction”, ”fixedVerifyCode” => YII_ENV_TEST ? ”testme” : null, ], ]; } public function actionIndex() { return $this->render(”index”); } public function actionLogin() { if (!Yii::$app->user->isGuest) { return $this->goHome(); } $model = new LoginForm(); if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->goBack(); } return $this->render(”login”, [ ”model” => $model, ]); } public function actionLogout() { Yii::$app->user->logout(); return $this->goHome(); } public function actionContact() { //load ContactForm model $model = new ContactForm(); //if there was a POST request, then try to load POST data into a model if ($model->load(Yii::$app->request->post()) && $model>contact(Yii::$app->params [”adminEmail”])) { Yii::$app->session->setFlash(”contactFormSubmitted”); return $this->refresh(); } return $this->render(”contact”, [ ”model” => $model, ]); } public function actionAbout() { return $this->render(”about”); } public function actionSpeak($message = “default message”) { return $this->render(“speak”,[”message” => $message]); } } ?> Run the basic application template using PHP built-in server and go to the web browser at http://localhost:8080/index.php?r=site/contact. You will see the following page − When you open this page, the contact action of the SiteController is executed. The code first loads the ContactForm model. Then it renders the contact view and passes the model into it. If you fill in the form and click the submit button, you will see the following − Notice that this time the following code is executed − if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app>params [”adminEmail”])) { Yii::$app->session->setFlash(”contactFormSubmitted”); return $this->refresh(); } If there was a POST request, we assign the POST data to the model and try to send an email. If we success then we set a flash message with the text “Thank you for contacting us. We will respond to you as soon as possible.” and refresh the page. Understanding Routes In the above example, in the URL, http://localhost:8080/index.php?r=site/contact, the route is site/contact. The contact action (actionContact) in the SiteController will be executed. A route consists of the following parts− moduleID − If the controller belongs to a module, then this part of the route exists. controllerID (site in the above example) − A unique string that identifies the controller among all controllers within the same module or application. actionID (contact in the above example) − A unique string that identifies the action among all actions within the same controller. The format of the route is controllerID/actionID. If the controller belongs to a module, then it has the following format: moduleID/controllerID/actionID. Print Page Previous Next Advertisements ”;
Yii – Widgets
Yii – Widgets ”; Previous Next A widget is a reusable client-side code, which contains HTML, CSS, and JS. This code includes minimal logic and is wrapped in a yiibaseWidget object. We can easily insert and apply this object in any view. Step 1 − To see widgets in action, create an actionTestWidget function in the SiteController with the following code. public function actionTestWidget() { return $this->render(”testwidget”); } In the above example, we just returned a View called “testwidget”. Step 2 − Now, inside the views/site folder, create a View file called testwidget.php. <?php use yiibootstrapProgress; ?> <?= Progress::widget([”percent” => 60, ”label” => ”Progress 60%”]) ?> Step 3 − If you go to http://localhost:8080/index.php?r=site/test-widget, you will see the progress bar widget. Using Widgets To use a widget in a View, you should call the yiibaseWidget::widget() function. This function takes a configuration array for initializing the widget. In the previous example, we inserted a progress bar with percent and labelled parameters of the configuration object. Some widgets take a block of content. It should be enclosed between yiibaseWidget::begin() and yiibaseWidget::end() functions. For example, the following widget displays a contact form − <?php $form = ActiveForm::begin([”id” => ”contact-form”]); ?> <?= $form->field($model, ”name”) ?> <?= $form->field($model, ”email”) ?> <?= $form->field($model, ”subject”) ?> <?= $form->field($model, ”body”)->textArea([”rows” => 6]) ?> <?= $form->field($model, ”verifyCode”)->widget(Captcha::className(), [ ”template” => ”<div class=”row”> <div class = “col-lg-3”>{image}</div> <div class = “col-lg-6″>{input}</div> </div>”, ]) ?> <div class = “form-group”> <?= Html::submitButton(”Submit”, [”class” => ”btn btn-primary”, ”name” => ”contact-button”]) ?> </div> <?php ActiveForm::end(); ?> Creating Widgets To create a widget, you should extend from yiibaseWidget. Then you should override the yiibaseWidget::init() and yiibaseWidget::run() functions. The run() function should return the rendering result. The init() function should normalize the widget properties. Step 1 − Create a components folder in the project root. Inside that folder, create a file called FirstWidget.php with the following code. <?php namespace appcomponents; use yiibaseWidget; class FirstWidget extends Widget { public $mes; public function init() { parent::init(); if ($this->mes === null) { $this->mes = ”First Widget”; } } public function run() { return “<h1>$this->mes</h1>”; } } ?> Step 2 − Modify the testwidget view in the following way. <?php use appcomponentsFirstWidget; ?> <?= FirstWidget∷widget() ?> Step 3 − Go to http://localhost:8080/index.php?r=site/test-widget. You will see the following. Step 4 − To enclose the content between the begin() and end() calls, you should modify the FirstWidget.php file. <?php namespace appcomponents; use yiibaseWidget; class FirstWidget extends Widget { public function init() { parent::init(); ob_start(); } public function run() { $content = ob_get_clean(); return “<h1>$content</h1>”; } } ?> Step 5 − Now h1 tags will surround all the content. Notice that we use the ob_start() function to buffer the output. Modify the testwidget view as given in the following code. <?php use appcomponentsFirstWidget; ?> <?php FirstWidget::begin(); ?> First Widget in H1 <?php FirstWidget::end(); ?> You will see the following output − Important Points Widgets should − Be created following the MVC pattern. You should keep presentation layers in views and logic in widget classes. Be designed to be self-contained. The end developer should be able to design it into a View. Print Page Previous Next Advertisements ”;
Yii – Using Actions
Yii – Using Actions ”; Previous Next To create an action in a controller class, you should define a public method whose name starts with the word action. The return data of an action represents the response to be sent to the end user. Step 1 − Let us define the hello-world action in our ExampleController. <?php namespace appcontrollers; use yiiwebController; class ExampleController extends Controller { public function actionIndex() { $message = “index action of the ExampleController”; return $this->render(“example”,[ ”message” => $message ]); } public function actionHelloWorld() { return “Hello world!”; } } ?> Step 2 − Type http://localhost:8080/index.php?r=example/hello-world in the address bar of the web browser. You will see the following. Action IDs are usually verbs, such as create, update, delete and so on. This is because actions are often designed to perform a particular change if a resource. Action IDs should contain only these characters − English letters in lower case, digits, hyphens, and underscores. There are two types of actions: inline and standalone. Inline actions are defined in the controller class. The names of the actions are derived from action IDs this way − Turn the first letter in all words of the action ID into uppercase. Remove hyphens. Add the action prefix. Examples − index becomes actionIndex. hello-world(as in the example above) becomes actionHelloWorld. If you plan to reuse the same action in different places, you should define it as a standalone action. Create a Standalone Action Class To create a standalone action class, you should extend yiibaseAction or a child class, and implement a run() method. Step 1 − Create a components folder inside your project root. Inside that folder create a file called GreetingAction.php with the following code. <?php namespace appcomponents; use yiibaseAction; class GreetingAction extends Action { public function run() { return “Greeting”; } } ?> We have just created a reusable action. To use it in our ExampleController, we should declare our action in the action map by overriding the actions() method. Step 2 − Modify the ExampleController.php file this way. <?php namespace appcontrollers; use yiiwebController; class ExampleController extends Controller { public function actions() { return [ ”greeting” => ”appcomponentsGreetingAction”, ]; } public function actionIndex() { $message = “index action of the ExampleController”; return $this->render(“example”,[ ”message” => $message ]); } public function actionHelloWorld() { return “Hello world!”; } } ?> The actions() method returns an array whose values are class names and keys are action IDs. Step 3 − Go to http://localhost:8080/index.php?r=example/greeting. You will see the following output. Step 4 − You can also use actions to redirect users to other URLs. Add the following action to the ExampleController.php. public function actionOpenGoogle() { // redirect the user browser to http://google.com return $this->redirect(”http://google.com”); } Now, if you open http://localhost:8080/index.php?r=example/open-google, you will be redirected to http://google.com. The action methods can take parameters, called action parameters. Their values are retrieved from $_GET using the parameter name as the key. Step 5 − Add the following action to our example controller. public function actionTestParams($first, $second) { return “$first $second”; } Step 6 − Type the URL http://localhost:8080/index.php?r=example/testparams&first=hello&second=world in the address bar of your web browser, you will see the following output. Each controller has a default action. When a route contains the controller ID only, it means that the default action is requested. By default, the action is index. You can easily override this property in the controller. Step 7 − Modify our ExampleController this way. <?php namespace appcontrollers; use yiiwebController; class ExampleController extends Controller { public $defaultAction = “hello-world”; /* other actions */ } ?> Step 8 − Now, if you go to http://localhost:8080/index.php?r=example, you will see the following. To fulfill the request, the controller will undergo the following lifecycle − The yiibaseController:init() method is called. The controller creates an action based on the action ID. The controller sequentially calls the beforeAction() method of the web application, module, and the controller. The controller runs the action. The controller sequentially calls the afterAction() method of the web application, module, and the controller. The application assigns action result to the response. Important Points The Controllers should − Be very thin. Each action should contain only a few lines of code. Use Views for responses. Not embed HTML. Access the request data. Call methods of models. Not process the request data. These should be processed in the model. Print Page Previous Next Advertisements ”;
Yii – Assets
Yii – Assets ”; Previous Next An asset is a file (css, js, video, audio or image, etc.) that may be referenced in a web page. Yii manages assets in asset bundles. The purpose of an asset bundle is to have a group of related JS or CSS files in the code base and to be able to register them within a single PHP call. Asset bundles can also depend on other asset bundles. Inside the assets folder, you will find the asset bundle for the basic application template − <?php namespace appassets; use yiiwebAssetBundle; /** * @author Qiang Xue <[email protected]> * @since 2.0 */ class AppAsset extends AssetBundle { public $basePath = ”@webroot”; public $baseUrl = ”@web”; public $css = [ ”css/site.css”, ]; public $js = []; public $depends = [ ”yiiwebYiiAsset”, ”yiibootstrapBootstrapAsset”, ]; } ?> The above class specifies that the asset files are located inside the @webroot folder, which corresponds to the URL @web. The bundle contains no JS files and a single CSS file. The bundle depends on other bundles − yiiwebYiiAsset and yiibootstrapBootstrapAsset. Properties of AssetBundle Following are the properties of AssetBundle. basePath − Defines a web-accessible directory that contains the asset files in this bundle. baseUrl − Specifies the URL corresponding to the basePath property. js − Defines an array of the JS files contained in this bundle. css − Defines an array of the CSS files contained in this bundle. depends − Defines an array of the asset bundles that this bundle depends on. It means that CSS and JS files of the current asset bundle will be included after the bundles, which are declared by the depends property. sourcePath − Defines the root directory that contains the asset files. You should set this property if the root directory is not web accessible. Otherwise, you should set the basePath and baseUrl properties. cssOptions − Defines the options that will be passed to the yiiwebView∷registerCssFile function. jsOptions − Defines the options that will be passed to the yiiwebView::registerJsFile function. publishOptions: Specifies the options that will be passed to the yiiwebAssetManager::publish function. Classification of Assets Depending on location, assets can be classified as − Source Assets − The assets are located in the directory that cannot be directly accessed via web. They should be copied to a web directory in order to use source assets in a page. This process is called asset publishing. Published Assets − The assets are located in a web accessible directory External Assets − The assets are located on another web server. Using Asset Bundles Step 1 − Inside the assets folder, create a new file called DemoAsset.php with the following content. <?php namespace appassets; use yiiwebAssetBundle; class DemoAsset extends AssetBundle { public $basePath = ‘@webroot’; public $baseUrl = ‘@web’; public $js = [‘js/demo.js’]; } ?> Step 2 − We have just declared a new asset bundle with a single demo.js file. Now, inside the web/js folder, create a file called demo.js with this code. console.log(“hello from demo asset”); Step 3 − To register the newly created asset bundle, go to the views/layouts directory and at the top of the main.php file, add the following line. appassetsDemoAsset::register($this); Step 4 − If point your web browser at http://localhost:8080/index.php, you should see the following chrome console output. You can also define the jsOptions and cssOptions properties to customize the way that CSS and JS files are included in a page. By default, JS files are included before the closing body tag. Step 5 − To include JS files in the head section, modify the DemoAsset.php file in the following way. <?php namespace appassets; use yiiwebAssetBundle; use yiiwebView; class DemoAsset extends AssetBundle { public $basePath = ”@webroot”; public $baseUrl = ”@web”; public $js = [”js/demo.js”]; public $jsOptions = [”position” => View::POS_HEAD]; } ?> Step 6 − Now go to http://localhost:8080/index.php, you should see that the demo.js script is included in the head section of the page. It is a common practice for a web application, running in production mode, to enable HTTP caching for assets. By doing so, the last modification timestamp will be appended to all published assets. Step 7 − Go to the config folder and modify the web.php file as shown in the following code. <?php $params = require(__DIR__ . ”/params.php”); $config = [ ”id” => ”basic”, ”basePath” => dirname(__DIR__), ”bootstrap” => [”log”], ”components” => [ ”assetManager” => [ ”appendTimestamp” => true, ], ”request” => [ // !!! insert a secret key in the following (if it is empty) – this is //required by cookie validation ”cookieValidationKey” => ”ymoaYrebZHa8gURuolioHGlK8fLXCKjO”, ], ”cache” => [ ”class” => ”yiicachingFileCache”, ], ”user” => [ ”identityClass” => ”appmodelsUser”, ”enableAutoLogin” => true, ], ”errorHandler” => [ ”errorAction” => ”site/error”, ], ”mailer” => [ ”class” => ”yiiswiftmailerMailer”, // send all mails to a file by default. You have to set // ”useFileTransport” to false and configure a transport // for the mailer to send real emails. ”useFileTransport” => true, ], ”log” => [ ”traceLevel” => YII_DEBUG ? 3 : 0, ”targets” => [ [ ”class” => ”yiilogFileTarget”, ”levels” => [”error”, ”warning”], ], ], ], ”db” => require(__DIR__ . ”/db.php”), ], ”modules” => [ ”hello” => [ ”class” => ”appmoduleshelloHello”, ], ], ”params” => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for ”dev” environment $config[”bootstrap”][] = ”debug”; $config[”modules”][”debug”] = [ ”class” => ”yiidebugModule”, ]; $config[”bootstrap”][] = ”gii”; $config[”modules”][”gii”] = [ ”class” => ”yiigiiModule”, ]; } return $config; ?> We have added the AssetManager component and set the appendTimestamp property. Step 8 − Now type http://localhost:8080/index.php in the address bar of the web browser. You will notice that all the assets now have a timestamp as shown in the following image. Core Yii Assetbundles Following are the Core Yii Assetbundles. yiiwebJqueryAsset − Includes the jquery.js file. yiiwebYiiAsset − Includes the yii.js file, which implements a mechanism of organizing JS code in modules. yiibootstrapBootstrapAsset − Includes the CSS file from the Twitter Bootstrap framework. yiibootstrapBootstrapPluginAsset − Includes the JS file from the Twitter Bootstrap framework.
Yii – Entry Scripts
Yii – Entry Scripts ”; Previous Next Entry scripts are responsible for starting a request handling cycle. They are just PHP scripts accessible by users. The following illustration shows the structure of an application − Web application (as well as console application) has a single entry script. The End user makes request to the entry script. Then the entry script instantiates application instances and forwards requests to them. Entry script for a console application is usually stored in a project base path and named as yii.php. Entry script for a web application must be stored under a web accessible directory. It is often called index.php. The Entry scripts do the following − Define constants. Register Composer autoloader. Include Yii files. Load configuration. Create and configure an application instance. Process the incoming request. The following is the entry script for the basic application template − <?php //defining global constants defined(”YII_DEBUG”) or define(”YII_DEBUG”, true); defined(”YII_ENV”) or define(”YII_ENV”, ”dev”); //register composer autoloader require(__DIR__ . ”/../vendor/autoload.php”); //include yii files require(__DIR__ . ”/../vendor/yiisoft/yii2/Yii.php”); //load application config $config = require(__DIR__ . ”/../config/web.php”); //create, config, and process reques (new yiiwebApplication($config))->run(); ?> The following is the entry script for the console application − #!/usr/bin/env php <?php /** * Yii console bootstrap file. * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ //defining global constants defined(”YII_DEBUG”) or define(”YII_DEBUG”, true); //register composer autoloader require(__DIR__ . ”/vendor/autoload.php”); require(__DIR__ . ”/vendor/yiisoft/yii2/Yii.php”); //load config $config = require(__DIR__ . ”/config/console.php”); //apply config the application instance $application = new yiiconsoleApplication($config); //process request $exitCode = $application->run(); exit($exitCode); ?> The best place for defining global constants is entry scripts. There are three supported by Yii constants − YII_DEBUG − Defines whether you are in debug mode or not. If set to true, then we will see more log data and detail error call stack. YII_ENV − Defines the environment mode. The default value is prod. Available values are prod, dev, and test. They are used in configuration files to define, for example, a different DB connection (local and remote) or other values. YII_ENABLE_ERROR_HANDLER − Specifies whether to enable the default Yii error handler. To define a global constant the following code is used − //defining global constants defined(”YII_DEBUG”) or define(”YII_DEBUG”, true); which is equivalent to: if(!defined(”YII_DEBUG”)) { define(”YII_DEBUG”, true); } Note − The global constants should be defined at the beginning of an entry script in order to take effect when other PHP files are included. Print Page Previous Next Advertisements ”;
Yii – Overview
Yii – Overview ”; Previous Next The Yii[ji:] framework is an open-source PHP framework for rapidly-developing, modern Web applications. It is built around the Model-View-Controller composite pattern. Yii provides secure and professional features to create robust projects rapidly. The Yii framework has a component-based architecture and a full solid caching support. Therefore, it is suitable for building all kinds of Web applications: forums, portals, content managements systems, RESTful services, e-commerce websites, and so forth. It also has a code generation tool called Gii that includes the full CRUD(Create-Read-Update-Delete) interface maker. Core Features The core features of Yii are as follows − Yii implements the MVC architectural pattern. It provides features for both relational and NoSQL databases. Yii never over-designs things for the sole purpose of following some design pattern. It is extremely extensible. Yii provides multi-tier caching support. Yii provides RESTful API development support. It has high performance. Overall, if all you need is a neat interface for the underlying database, then Yii is the right choice. Currently, Yii has two versions: 1.1 and 2.0. Version 1.1 is now in maintenance mode and Version 2 adopts the latest technologies, including Composer utility for package distribution, PSR levels 1, 2, and 4, and many PHP 5.4+ features. It is version 2 that will receive the main development effort over the next few years. Yii is a pure OOP (Object-Oriented Programming) framework. Hence, it requires a basic knowledge of OOP. The Yii framework also uses the latest features of PHP, like traits and namespaces. It would be easier for you to pick up Yii 2.0 if you understand these concepts. Environment The major requirements for Yii2 are PHP 5.4+ and a web server. Yii is a powerful console tool, which manages database migrations, asset compilation, and other stuff. It is recommended to have a command line access to the machine where you develop your application. For development purpose, we will use − Linux Mint 17.1 PHP 5.5.9 PHP built-in web server Pre-installation check To check whether your local machine is good to go with the latest Yii2 version, do the following − Step 1 − Install the latest php version. sudo apt-get install php5 Step 2 − Install the latest mysql version. sudo apt-get install mysql-server Step 3 − Download the Yii2 basic application template. composer create-project –prefer-dist –stability=dev yiisoft/yii2-app-basic basic Step 4 − To start a PHP built-in server, inside the basic folder run. php -S localhost:8080 There is a useful script, requirements.php. It checks whether your server meets the requirements to run the application. You can find this script in the root folder of your application. If you type http://localhost:8080/requirements.php in the address bar of the web browser, the page looks like as shown in the following screenshot − Print Page Previous Next Advertisements ”;
Yii – Create Page
Yii – Create Page ”; Previous Next Now we are going to create a “Hello world” page in your application. To create a page, we must create an action and a view. Actions are declared in controllers. The end user will receive the execution result of an action. Step 1 − Declare the speak action in the existing SiteController, which is defined in the class file controllers/SiteController.php. <?php namespace appcontrollers; use Yii; use yiifiltersAccessControl; use yiiwebController; use yiifiltersVerbFilter; use appmodelsLoginForm; use appmodelsContactForm; class SiteController extends Controller { /* other code */ public function actionSpeak($message = “default message”) { return $this->render(“speak”,[”message” => $message]); } } ?> We defined the speak action as a method called actionSpeak. In Yii, all action methods are prefixed with the word action. This is how the framework differentiates action methods from non-action ones. If an action ID requires multiple words, then they will be concatenated by dashes. Hence, the action ID add-post corresponds to the action method actionAddPost. In the code given above, the ‘out’ function takes a GET parameter, $message. We also call a method named ‘render’ to render a view file called speak. We pass the message parameter to the view. The rendering result is a complete HTML page. View is a script that generates a response”s content. For the speak action, we create a speak view that prints our message. When the render method is called, it looks for a PHP file names as view/controllerID/vewName.php. Step 2 − Therefore, inside the views/site folder create a file called speak.php with the following code. <?php use yiihelpersHtml; ?> <?php echo Html::encode($message); ?> Note that we HTML-encode the message parameter before printing to avoid XSS attack. Step 3 − Type the following in your web browser http://localhost:8080/index.php?r=site/speak&message=hello%20world. You will see the following window − The ‘r’ parameter in the URL stands for route. The route”s default format is controllerID/actionID. In our case, the route site/speak will be resolved by the SiteController class and the speak action. Print Page Previous Next Advertisements ”;
Yii – Application Structure
Yii – Application Structure ”; Previous Next There is only one folder in the overall code base that is publicly available for the web server. It is the web directory. Other folders outside the web root directory are out of reach for the web server. Note − All project dependencies are located in the composer.json file. Yii2 has a few important packages that are already included in your project by Composer. These packages are the following − Gii – The code generator tool The debug console The Codeception testing framework The SwiftMailer library The Twitter Bootstrap UI library The first three packages are only useful in the development environment. Yii2”s application structure is precise and clear. It contains the following folders − Assets − This folder includes all .js and .css files referenced in the web page. Commands − This folder includes the controllers that can be used from the terminal. Config − This folder contains config files for managing database, application and application parameters. Mail − This folder includes the mail layout. Models − This folder includes the models used in the application. Runtime − This folder is for storing runtime data. Tests − This folder includes all the tests (acceptance, unit, functional). Vendor − This folder contains all the third-party packages managed by Composer. Views − This folder is for views, that are displayed by the controllers. The layout folder is a for page template. Web − The entry point from web. Application Structure Following is the diagrammatic representation of the application structure. Yii2 – Objects The following list contains all Yii2”s objects − Models, Views, and Controllers Models are for data representation (usually from the database). View are for displaying the data. Controllers are for processing requests and generating responses. Components To create a reusable functionality, the user can write his own components. Components are just objects that contain logic. For example, a component could be a weight converter. Application components These are objects that instanced just one time in the whole application. The main difference between Components and Application components is that the latter can have only one instance in the whole application. Widgets Widgets are reusable objects containing both logic and rendering code. A widget could be, for example, a gallery slider. Filters Filters are objects that run before or after the execution of the Controller actions. Modules You can consider Modules as reusable subapps, containing Models, Views, Controllers, and so forth. Extensions Extensions are packages that can be managed by the Composer. Print Page Previous Next Advertisements ”;