You get a bonus - 1 coin for daily activity. Now you have 1 coin

Basics of the Yii Framework

Lecture




Basics of the Yii Framework

Yii Framework is one of the best PHP frameworks for developing large web applications. In the cycle “Yii Framework for Dummies”, we will learn how to deploy a yii application on a server, learn how to work with the framework and learn about the main features it provides. I will try to tell all this as simply and clearly as possible.

Sweep Yii applications


In order to use the Yii Framework, you need:

  1. Web server with pre-installed PHP version 5.1 and higher.
  2. Basic knowledge of PHP, object-oriented programming and MVC pattern.
  3. Archive with the framework itself. You can download from the official site.


The downloaded archive contains the following elements:

  1. Text files CHANGELOG, LICENSE, README, and UPGRADE, the contents of which are evident from the titles.
  2. The demos folder containing four demo projects (a blog, a phone book, the Hangman game and a simple “Hello, world!” Game).
  3. Folder framework with the framework itself.
  4. The requirements folder with the framework and hosting compatibility tests.


We assume that we are working in the operating system of the UNIX family and the path to our site:

/srv/www/site.com/

To prevent the framework files from being accessible from the browser, place the framework folder in the directory

/ srv / www /

In order to deploy a yii application, use the command line. From the root, execute the following commands in the terminal:

cd /srv/www/site.com/framework/
php -f yiic web

app /srv/www/site.comAt the same time, a demonstration yii application will be deployed in the site folder and the required permissions for folders and files will be set.

Structure of Yii application


Consider the folders in the /srv/www/site.com/ directory

  1. assests - files that the framework generates in the process.
  2. css - styles.
  3. images - images.
  4. protected - the main application folder. We will consider it in more detail.
  5. themes - framework theme


Consider folders in the /srv/www/yoursite.com/protected/ directory.

  1. commands - framework management applications via the console.
  2. components - various components.
  3. config - configuration files.
  4. controllers - controllers (MVC).
  5. data - SQLite database.
  6. etensions are extensions for the framework.
  7. messages - multilanguage.
  8. migrations - migrations.
  9. models - models (MVC).
  10. runtime - temporary files created by the framework.
  11. tests - tests.
  12. views - views (MVC).

Setting up a Yii application


Any user interactions in the yii application occur via the bootstrap index.php file.

$yii=dirname(__FILE__).'/../../framework/yii.php'; //Определяем расположение фреймворка $config=dirname(__FILE__).'/protected/config/main.php'; //Определяем местоположение файла конфигурации defined('YII_DEBUG') or define('YII_DEBUG',true); //Режим отладки defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3); //Определение количества уровней в стеке вызовов, которые будут отображаться в логах. Стек вызовов - это история подключения файлов и функций require_once($yii); Yii::createWebApplication($config)->run(); //Запускаем приложение 


Most of the settings are in the /config/main.php file. The configuration file returns a multidimensional associative array of settings, some of which are predefined by default.

 return array ( 'name'=>'Мой первый сайт на Yii Framework!', // Название приложения 'defaultController' => 'site', // Контроллер, загружаемый по умолчанию 'modules'=>array( 'gii'=>array( // Модуль генерации кода, который можно использовать 'class'=>'system.gii.GiiModule', 'password'=>'YourPassword', 'ipFilters'=>array(), ), ), 'components'=>array( 'urlManager'=>array( // Компонент, изменяющий URL-адреса 'urlFormat'=>'path', 'rules'=>array( '/'=>'/view', '//'=>'/', '/'=>'/', ), ), 'db'=>array( // Параметры доступа к MySQL базе данных 'connectionString' => 'mysql:host=localhost;dbname=mydatabase', 'emulatePrepare' => true, 'username' => 'root', 'password' => 'mypassword', 'charset' => 'utf8', ), ), 'params'=>array( // Параметры. Можно вызывать как Yii::app()->params['Имя параметра'] 'adminEmail'=>'my@email.com', ), ); 

Creating a database for the future application


As an example, we will work with a database containing some similarity of habr-comments and habr-users. It can be visualized as follows:

Basics of the Yii Framework

SQL queries to create corresponding tables:

 CREATE TABLE Users ( id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, username VARCHAR(20) NOT NULL, email VARCHAR(60) NOT NULL, karma SMALLINT NULL, raiting SMALLINT NULL, registerDate DATETIME NULL ) CREATE TABLE Comments ( id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, user MEDINT UNSIGNED NOT NULL, raiting SMALLINT NULL, date DATETIME NULL ) 

Conclusion


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Famworks

Terms: Famworks