Programming with YII2: getting started

  • Tutorial
image
From the translator.
Life is such a thing, somehow I started a series of articles on Java Spring and the community reported that the choice fell not on the latest information. Now life has thrown me into hardcore C ++ programming, but my soul still needs the web, so in my free time I decided to study technologies that any hosting can eat and at the same time the complexity of the developed applications and OOP will not be much affected PHP
The source code of the article in English can be found at http://code.tutsplus.com/tutorials/programming-with-yii2-getting-started--cms-22440 The
translation does not pretend to be verbatim, but about serious errors, if any - please inform in the comments.

If you ask “what is YII?”, Read the earlier lesson “Introduction to the YII framework”, which describes the benefits of YII and also addresses the issue of innovations of the second version of the framework dated October 12, 2014.
This lesson is about installing YII2, setting up your environment, writing the classic application “Hello world!”, setting up a remote environment for hosting and deployment from GitHub.

Install YII2


Documentation

You can find detailed instructions here , but I will go over the simple and typical installation and setup of the environment for Mac OS X. The framework has detailed documentation and a description of the classes , which contains all the details about YII.
From the translator. I, in turn, do not have an apple device on hand and I will do all the actions under Ubuntu (running under VMWare Player).

Install Composer

For comfortable use of the framework, it is recommended to use the popular PHP extension manager - Composer . If it is not already installed, do the following:
curl -s http://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer


Install YII2

Now use Composer to install YII2. To install, you need an account on GitHub , if you do not have one, register.
Let's call our first project “hello”:
cd ~/Sites
composer global require "fxp/composer-asset-plugin:1.0.0-beta2"
composer create-project --prefer-dist yiisoft/yii2-app-basic hello

YII2 supports two types of development applications: simple and advanced. For this lesson we will use a simple application, it is installed by default. The advanced application template supports front-end, back-end and console, just like WordPress, it is the administrative panel and tasks for cron.

Install and configure the local development environment

I use the open source MAMP for OS X freeware for development. Make sure that MAMP is running and its web server and database server are running. Then create a symbolic link to the directory with the site:
cd /Applications/MAMP/htdocs
ln -s ~/Sites/hello/ /Applications/MAMP/htdocs/hello

Now, if you've set up all right, then open localhost : 8888 / hello / web, you will see a simple YII2 application template with Bootstrap 3.x .
image
This page will surprise developers who were previously developing on YII 1.1, where the latest version of Bootstrap was not preinstalled, which has firmly taken its place on the network.

YII application architecture

One of the key features of the framework is support for the MVC pattern . This allows you to create more structured code that is easier to understand, simplifies many things that are hard to implement in PHP, such as security and automatic code generation. It also helps maintain and reuse code.
In a YII application, all traffic is directed to a single /web/index.php file. This file loads YII, dependencies, and then launches our application.
run();

By default, this is the Index method in the file /controllers/SiteController.php
public function actionIndex()
    {
        return $this->render('index');
    }

Typically, controllers have many methods, but with a minimal amount of code. Controllers control access, load models and views. The main semantic load should lie on models, and representations only display patterns.
By default, YII displays /views/layouts/main.php as a view for /views/site/index.php. main.php supports html and css page structure with toolbar and content. Inside main.php, the content is called:
isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [], ]) ?>

The $ content variable will be replaced by the code generated in /views/site/index.php, which represents a static html page.

We are writing the application “Hello world!”


Include beautiful urls

First, let's enable some pretty addresses with mod_rewrite. If on the home page you click on the about button, you will see an address similar to this: localhost : 8888 / hello / web / index.php? R = site% 2Fabout. Now we will bring it to this form localhost : 8888 / hello / web / site / about.
The config directory contains settings for your entire environment: web application, console application settings and database settings. Change the file /config/web.php as follows:
'components' => [
//...
  'urlManager' => [
          'showScriptName' => false,
          'enablePrettyUrl' => true
                  ],    
//...
'request' => [

Then you need to create in the / web directory where our index.php is stored, the .htaccsess file, with the following contents:
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php

Make sure that mod_rewrite is enabled in MAMP, if you have problems, look at the branch on stackoverflow .
In your browser, go to localhost : 8888 / hello / web / site / about, now you should see the About page of a simple YII application there.

Create action

The next step is to create an action for the controller, named Say, to repeat our message. In the file /controllers/SiteController.php add the following:
public function actionSay($target = 'World')
{
    return $this->render('say', ['target' => $target]);
}

This function will look for the target parameter in the url address to display it on the screen. If it is absent, simply “World” will be displayed. In the YII framework, actions are implemented as methods prefixed by actionNameEkshena. In the SiteController class, we used the public function actionSay to create a Say action.
The standard behavior of the render method is to search for a file in views / ControllerID / ViewName.php so let's create a say.php file in / views / site /:

Hello

Welcome to your Yii2 demonstration application.


This template will print the string “Hello + $ (target)”, where $ (target) is the variable passed to url. To ensure security, it does not fall directly into a line, but at the beginning it is checked for malicious code.
If you now visit localhost : 8888 / hello / web / site / say? Target = Tuts% 20Readers, you will see the following:
image
This is a simple example of implementing the MVC framework model. In more detail you can familiarize yourself with this example on the framework website in the official documentation .
Now, let's upload our application on GitHub and run it on the production server.

Setting up your remote environment


A simple YII application should run on the Apache and Nginx servers “out of the box”, I will give instructions on how to run on Apache, about Nginx you can find here .

Create a repository on GitHub

Once I installed the basic YII template, I create a repository on GitHub :
image
Attention: It is much easier to copy and paste YII .gitignore from GitHub (https://github.com/yiisoft/yii2/blob/master/.gitignore) into the local folder ~ /Sites/hello/.gitignore than to manually remove the excess. Although both options are valid.
I am using the GitHub Mac OS X application (https://mac.github.com/), although you can also use the command line to initialize the repository. For example, like this (replace "youraccount" with your name on GitHub:
cd ~/Sites/hello
git init
git commit -m "first commit of hello world for yii2"
git remote add origin git@github.com:youraccount/hello.git
git push -u origin master

From the translator. I prefer to use Bitbucket as a repository, as it allows you to have private repositories for free.
Configuring Apache on the server
If you have not yet configured the server, I recommend that you look at the instructions for configuring the server on Ubuntu (http://jeffreifman.com/digitalocean). If you have an IP address, configure your server’s DNS:
yourdomain.com A 192.161.234.17

Now login remotely via ssh to your server using IP or domain name
ssh root@yourserver.com

Update the configuration, install Git, enable mod_rewrite for Apache and mcrypt for PHP.
sudo apt-get update
sudo apt-get upgrade
sudo a2enmod rewrite
php5enmod mcrypt

Configuring remote server access to GitHub
Now we will configure pull requests from GitHub. Install Git First
sudo apt-get install git

Now we will create a group for www, add data and GitHub users and configure their rights:
adduser github
addgroup www 
adduser github www
adduser www-data www
chown -R :www /var/www
chmod +s -R /var/www
chmod -vR g+w /var/www/

Now create a key to synchronize with the repository:
su github
ssh-keygen -t rsa -C "yourgithubaccount@youremail.com"
exit
cat /home/github/.ssh/id_rsa.pub

You will see something similar to this, you need to copy and paste this key on GitHub
(if you encounter a problem, see here (https://help.github.com/articles/error-permission-denied-publickey/)):
image
Go to the settings section repository and add this key:
image
Then you will see something like this:
image
Finally you can clone the branch to your server:
git clone git@github.com:youraccount/hello.git /var/www/hello

If everything is correctly configured, you will see:
image
As the amount of code increases, you can easily synchronize the code of the local machine and the production server through the repository. This is much easier than synchronizing with the archive or manually, you will see for yourself in the process of further training.
Creating a site configuration for Apache
Create a configuration file:
nano /etc/apache2/sites-available/hello.conf

Change the domain name to your:

 ServerName yourdomain.com
# Set document root to be "basic/web"
DocumentRoot "/var/www/hello/web"

    # use mod_rewrite for pretty URL support
    RewriteEngine on
    # If a directory or a file exists, use the request directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # Otherwise forward the request to index.php
    RewriteRule . index.php

Turn on your site:
a2ensite hello.conf
a2dissite 000-default.conf 
service apache2 reload

Make sure that your application works by clicking on the link yourdomain.com/site/say?target=World ! (The debugging toolbar at the bottom of the page will be disabled!)
image
Congratulations! Now we are ready to start studying the more complex features of the framework!

Also popular now: