Разработка на Yii
Презентация на тему Разработка на Yii к уроку по информатике
Презентация по слайдам:
Слайд #1
Разработка на Yii QuartSoft Corp. Системный архитектор Климов П.В.

Слайд #2
Yii – PHP Framework ООП Модульность Простота Высокое быстродействие Основные характеристики:

Слайд #3
Prado Ruby on Rails jQuery Symfony Joomla Истоки Yii:

Слайд #4
Магия в PHP class Component { public $publicProperty; protected $_protectedProperty; public function setProtectedProperty($value) { $this->_protectedProperty = $value; return true; } public function getProtectedProperty() { return $this->_protectedProperty; } }

Слайд #5
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}'!"); } }

Слайд #6
$component = new Component(); $component->publicProperty = 'Public value'; echo($component->publicProperty); $component->protectedProperty = 'Protected value'; echo($component->protectedProperty);

Слайд #7
Автозагрузка классов 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:

Слайд #8
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(); } }

Слайд #9
Автозагрузка классов в контексте 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’, «Карта» автозагрузки классов:

Слайд #10
Порождение компонентов 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; }

Слайд #11
Задание любого объекта через массив: $componentConfig = array( 'class'=>'CUrlManager', 'urlFormat'=>'path', 'showScriptName'=>false, 'rules'=>array( '/'=>'site/index', '/*'=>'/view', ), ); $component = createComponent($componentConfig);

Слайд #12
Фабрика компонентов

Слайд #13
Одиночка (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();

Слайд #14
Фабрика компонентов(Component Factory) + Одиночка (Singleton) = Приложение Yii (Yii Application)

Слайд #15
$config = array( 'name'=>'My Web Application', … 'components'=>array( 'user'=>array( 'allowAutoLogin'=>true, ), … ), ); Yii::createWebApplication($config)->run(); … $application = Yii::app(); $user = Yii::app()->getComponent(‘user’);

Слайд #16
MVC в Yii

Слайд #17
Маршрутизация web запроса

Слайд #18
Доступ к базе данных через PDO

Слайд #19
Абстракция базы данных

Слайд #20
Active Record

Слайд #21
$allUsers = User::model()->findAll(); $newUser = new User(); $newUser->name = ‘new user’; $newUser->save(); $existingUser = User::model()->findByName(‘testuser’); $existingUser->email = ‘newemail@domain.com’; $existingUser->save();

Слайд #22
События (Events) в Yii

Слайд #23
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’

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

Слайд #25
Поведение (Behavior)

Слайд #26
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’

Слайд #27
Yii Динамический код Компонентная структура Приложение = «одиночка» + «фабрика» Отложенная загрузка и создание объектов MVC «PDO» и «Active Record» События Поведения
