Top Banner
Разработка на Yii QuartSoft Corp. Системный архитектор Климов П.В.
27

Yii development

May 11, 2015

Download

Technology

MageCloud
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Yii development

Разработка на Yii

QuartSoft Corp.

Системный архитектор

Климов П.В.

Page 2: Yii development

Yii – PHP Framework

• ООП

• Модульность

• Простота

• Высокое быстродействие

Основные характеристики:

Page 3: Yii development

• Prado

• Ruby on Rails

• jQuery

• Symfony

• Joomla

Истоки Yii:

Page 4: Yii development

Магия в PHPclass Component { public $publicProperty; protected $_protectedProperty; public function setProtectedProperty($value) { $this->_protectedProperty = $value; return true; } public function getProtectedProperty() { return $this->_protectedProperty; }}

Page 5: Yii development

class Component { public function __get($propertyName) { $methodName = 'get'.$propertyName; if (method_exists($this, $methodName)) { return call_user_func( array($this, $methodName) ); } else { throw new Exception("Missing property {$propertyName}'!"); } } public function __set($propertyName, $value) { $methodName = 'set'.$propertyName; if (method_exists($this, $methodName)) { return call_user_func( array($this, $methodName), $value ); } else { throw new Exception("Missing property {$propertyName}'!"); } }

Page 6: Yii development

$component = new Component();

$component->publicProperty = 'Public value';

echo($component->publicProperty);

$component->protectedProperty = 'Protected value';

echo($component->protectedProperty);

Page 7: Yii development

Автозагрузка классов

require_once('components/SomeClass.php');

$someObj = new SomeClass();

require_once('components/OtherClass.php');

$otherObj = new OtherClass();

require_once('components/SomeClass.php');

$anotherSomeObj = new SomeClass();

Подключение файлов по принципу DLL:

Page 8: Yii development

class Autoloader { public function autoload($className) { $classFileName = ‘components/'.$className.'.php'; if (file_exists($classFileName)) { require_once($classFileName); return true; } return false; }

public function register() { return spl_autoload_register( array($this, 'autoload') ); }

public function __construct() { $this->register(); } }

Page 9: Yii development

Автозагрузка классов в контексте Yii:

Yii::import(‘application.components.SomeClass');

Yii::import(‘application.components.OtherClass');

$someObj = new SomeClass();

‘SomeComponent’ => ‘/home/www/…/components/SomeClass.php’,

‘OtherComponent’ => ‘/home/www/…/components/OtherClass.php’,

«Карта» автозагрузки классов:

Page 10: Yii development

Порождение компонентов function createComponent(array $componentConfig) { $className = $componentConfig['class']; if (empty($className)) { throw new Exception(‘Missing parameter "class"!'); } unset($componentConfig['class']); if (!class_exists($className)) { Yii::import($className); // Автозагрузка } $component = new $className(); foreach($componentConfig as $name=>$value) { $component->$name = $value; // Конфигурация } return $component;}

Page 11: Yii development

$componentConfig = array( 'class'=>'CUrlManager', 'urlFormat'=>'path', 'showScriptName'=>false, 'rules'=>array( '/'=>'site/index', '<controller:\w+>/<id:\d+>*'=>'<controller>/view', ),);

$component = createComponent($componentConfig);

Задание любого объекта через массив:

Page 12: Yii development

Фабрика компонентов

Component

Factory$componentsConfig$components

*1“Create and store by name”

ComponentA ComponentB

Client

createComponent()getComponent()

“Request component by name”

Page 13: Yii development

Одиночка (Singleton)class Singleton { private static $_selfInstance = null; public static function getInstance() { if (!is_object(self::$_selfInstance)) { self::$_selfInstance = new Singleton(); } return self::$_selfInstance; } private function __construct() { // закрытый конструктор }}

$singleton = Singleton::getInstance();

Page 14: Yii development

Фабрика компонентов(Component Factory)

+Одиночка (Singleton)

=Приложение Yii (Yii Application)

Page 15: Yii development

$config = array('name'=>'My Web Application',

… 'components'=>array(

'user'=>array( 'allowAutoLogin'=>true,),

… ),);Yii::createWebApplication($config)->run();…$application = Yii::app();$user = Yii::app()->getComponent(‘user’);

Page 16: Yii development

MVC в Yii

Controller

Widget

Model View

ApplicationApplication

Components

Page 17: Yii development

Маршрутизация web запроса:Application

:Request

:UrlManager

:Controller

Apache‘run’

‘get request’

‘get route by request’

‘controller/action’

‘run action’

‘output’

‘request’

Page 18: Yii development

Доступ к базе данных через PDO

PDOClient PDO Driver

PDO MySQL PDO PostgreSQL …

1 1

MySQL PostgreSQL

Page 19: Yii development

Абстракция базы данных

PDO

Client

1DbConnection

DbSchema

Schema MySQL Schema PostgreSQL

1

DbCommand

“Control information”1

1“Compose

and execute queries”

* 1

Page 20: Yii development

Active Record

ActiveRecord

ActiveFinder

insert()update()delete()

find()populateRecord()

Client

DbCommand

“Find self instances”

“Instantiate by query result”

“Database access”

“Database access”

1

*

*

1

1

1* *

Page 21: Yii development

$allUsers = User::model()->findAll();

$newUser = new User();

$newUser->name = ‘new user’;

$newUser->save();

$existingUser = User::model()->findByName(‘testuser’);

$existingUser->email = ‘[email protected]’;

$existingUser->save();

Page 22: Yii development

События (Events) в Yii

Component

raiseEvent()

eventHandlers

Event

senderdata

Handler

*

*

1

11

*

“Raise”

“Handle”

“List of PHP callbacks”

PHP Callback

Page 23: Yii development

function handleBeforeSave(CEvent $event) {

$sender = $event->sender;

// Изменяем состояние отправителя события:

$sender->create_date = date('Y-m-d H:i:s', strtotime('NOW'));

}

$user = new User();

// Назначаем обработчик события:

$user->onBeforeSave = ‘handleBeforeSave’;

$user->name = ‘test name’;

$user->save();

echo $user->create_date; // Вывод: ‘2012-03-22 16:42’

Page 24: Yii development

Проблема множественного наследования

ActiveRecord

ArPositionSave custom records display order

ArFileBind physical file with the db record

ArPositionFilePosition + File

Page 25: Yii development

Поведение (Behavior)

Component

__call()attachBehavior()

behaviors

Behavior

getOwner()events()

owner

1*

Event

data

1 1

* *“Raise” “Handle”

Page 26: Yii development

class ArBehaviorExample extends CBehavior { public function behaviorMethod() { $owner = $this->getOwner(); $owner->create_date = date('Y-m-d H:i:s', strtotime('NOW')); }}

$user = new User();// Добавляем поведение:$behavior = new ArBehaviorExample();$user->attachBehavior($behavior);

// Вызываем метод поведения:$user->behaviorMethod();echo $user->create_date; // Вывод: ‘2012-03-22 16:46’

Page 27: Yii development

Yii• Динамический код• Компонентная структура• Приложение = «одиночка» + «фабрика»• Отложенная загрузка и создание

объектов• MVC• «PDO» и «Active Record»• События• Поведения