YII First ExampleAfter installing Yii, you can develop an application that can be accessed via URL http://hostname/basic/web/index.php or http://hostname/index.php depending upon your configuration. We'll run a basic example of Hello World on Yii2. Step1 Declaring action in controllersWe are creating an action called example. This action will read a message parameter from the request and will display that message. Action is always declared in the Controllers file. Here, we are not creating a new file and is declaring this action in the existing SiteController.php. Following is the starting code in SiteController.php file. Look at the above code, example action is defined as a method named actionExample. Prefix action is used to differentiate action methods from non-action methods. Name after the prefix action denotes the action's ID. Here we're taking a parameter $message, whose value is "Hello". If a request is sent with a message parameter in the URL with a different value say "Hyii", then this value will be displayed in the output. If no message parameter request is made in the URL, then "Hello" will be printed. Function render() is called to display view file named example.php. This result will be displayed to the end user in the browser. Step1 Creating View fileView folder basically contains the response content which will be delivered to the user on their request. In this example, we have created a file named example.php in the view/site folder. Following is the code of example.php file. Look at the above code, the message parameter is HTML encoded before being printed to prevent from XSS attack. Step1 Running on BrowserAccess the page with the following URL: http://localhost/hello/frontend/web/index.php?r=site%2Fexample&message=Hello+World output is shown below. Look at the above snapshot, output displays Hello World. In the URL, we have requested for message parameter. If we'll omit the message parameter in the URL, then our URL will be: http://localhost/hello/frontend/web/index.php?r=site%2Fexample and our Output will be only "Hello". In the URL, we have mentioned an r parameter. This r denotes to route. It's format is ControllerID/AtionID. In this example route denotes site/example. Next TopicWhat is Gii |