Plan prezentacji Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak Wyższa Szkoła Zarządzania i Bankowości w Krakowie http://artemis.wszib.edu.pl/~polak/ Wstęp Przykłady Kontroler Model Widok Klasy wspomagające Kontrola dostępu (ACL) Programowanie sterowane testami Dr inż. Stanisław Polak 1 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 2 Przedmiot: Aplikacje internetowe Wstęp Charakterystyka Wstęp Przydatne adresy CakePHP PHP 5.2.8 MVC http://cakephp.org/ http://book.cakephp.org/ http://api.cakephp.org/ http://bakery.cakephp.org/ Active Record CRUD Formularze HTML, skrypty JavaScript - XML, RSS oraz AJAX ACL Rusztowanie Kontrola i walidacja danych Mechanizmy zabezpieczeń i zarządzania sesjami Szablony Inspirowany Ruby on Rails (RoR) Dr inż. Stanisław Polak Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 4 Przedmiot: Aplikacje internetowe
Charakterystyka Wstęp Ranking popularności frameworków webowych Charakterystyka Wstęp CakePHP na tle innych frameworków PHP Źródło: http://www.bestwebframeworks.com/compare-web-frameworks/php/ Źródło: http://hotframeworks.com/ Dr inż. Stanisław Polak 5 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 6 Przedmiot: Aplikacje internetowe Charakterystyka Wstęp Struktura Charakterystyka Wstęp Typowe żądanie Przykładowy adres strony: http://www.example.com/ cakes / buy / 1 Kontrolery Widoki Modele Komponenty (Components) Pomocnicy (Helpers) Zachowania (Behaviors) Czarny kolor elementy wymagane. Szary kolor elementy opcjonalne, niebieski kolor funkcje wywołań zwrotnych Dr inż. Stanisław Polak 7 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 8 Przedmiot: Aplikacje internetowe
Instalacja i konfiguracja Wstęp Instalacja Instalacja i konfiguracja Wstęp Ogólna struktura katalogu z instalacją CakePHP / Źródła: http://www.cakephp.org/ Wymagania dla serwera Apache Moduł mod rewrite Włączenie obsługi plików.htaccess AllowOverride All tmp $USER httpd 1 cd /tmp / $USER / httpd / htdocs 2 unzip cakephp. zip mv cakephp cakephp Typy instalacji Rozwojowa http://localhost:8080/cakephp/ Produkcyjna DocumentRoot /tmp/twójlogin/httpd/htdocs/cakephp/app/webroot http://localhost:8080/ Zaawansowana htdocs cakephp app.htaccess index.php lib plugins README.md vendors Dr inż. Stanisław Polak 9 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 10 Przedmiot: Aplikacje internetowe Instalacja i konfiguracja Wstęp Ogólna struktura katalogu z kodem aplikacji CakePHP Instalacja i konfiguracja Wstęp Ważniejsze pliki konfiguracyjne cakephp app Config Console Controller.htaccess index.php Lib Locale Model Plugin Test tmp app Config bootstrap.php core.php database.php routes.php 2 class DATABASE_CONFIG { public $default = array ( 4 datasource => Database / Mysql, 5 persistent => false, 6 host => localhost, 7 login => user, 8 password => password, 9 database => database_name, 10 prefix =>, 11 // e n c o d i n g => u t f 8, 12 ) ; 1 14 public $test = array ( datasource => Database / Sqlite,... ) ; 15 } 16?> public $usedbconfig = test ; Vendor View webroot Dr inż. Stanisław Polak 11 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 12 Przedmiot: Aplikacje internetowe
Konwencje nazewnicze Wstęp Konwencje dla klas i plików Konwencje nazewnicze Wstęp Konwencje dla modeli i BD Nazwa modelu Apple BigAuthor Nazwa tabeli apples big authors Typ Nazwa klasy Nazwa pliku z definicją klasy Kontroler KissesAndHugsController KissesAndHugsController.php Komponent MyHandyComponent MyHandyComponent.php Model OptionValue OptionValue.php Zachowanie EspeciallyFunkableBehavior EspeciallyFunkableBehavior.php Widok SuperSimpleView SuperSimpleView.php Pomocnik BestEverHelper BestEverHelper.php class Apple extends AppModel { 4... 5 } 6?> id producer id name 1 4 Jonatan......... Tabela : apples app/model/apple.php id name...... 4 Kowalski...... Tabela : producers Dr inż. Stanisław Polak 1 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 14 Przedmiot: Aplikacje internetowe Konwencje nazewnicze Wstęp Konwencje dla kontrolerów class ApplesController extends AppController { 4 #Request h t t p : / / l o c a l h o s t :8080/ a p p l e s / 5 function index ( ) {... } 6 7 #Request h t t p : / / l o c a l h o s t :8080/ a p p l e s / getready / 8 function getready ( ) {... } 9 10 #Request h t t p : / / l o c a l h o s t :8080/ a p p l e s / f i n d N e w A p p l e s E r r o r 11 function _findnewapples ( ) {... } 12 1 #Request h t t p : / / l o c a l h o s t :8080/ a p p l e s / l a t e s t e l e m e n t / 14 function latest_element ( ) { 15 $this >_findnewapples ( ) ; 16 } 17 } app/controller/applescontroller.php Konwencje nazewnicze Wstęp Konwencje dla widoków 1 <html> 2 <?php... 4?> 5 </html> app/view/apples/index.ctp class ApplesController extends AppController { 4 #Request http : / / localhost :8080/ apples / 5 function index(){} 6 #Request http : / / localhost :8080/ apples / getready / 7 function getready(){} 8 } class Apple extends AppModel { 4... 5 } 6?> app/model/apple.php 1 <html> 2 <?php... 4?> 5 </html> app/controller/applescontroller.php app/view/apples/get ready.ctp id producer id name......... Tabela : apples Dr inż. Stanisław Polak 15 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 16 Przedmiot: Aplikacje internetowe
Hello World Przykłady Aplikacja Hello World Hello World Przykłady Widok 1 Hello World app/view/hellos/index.ctp Dr inż. Stanisław Polak 17 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 18 Przedmiot: Aplikacje internetowe Hello World Przykłady Model Hello World Przykłady Kontroler 2 App : : uses ( AppModel, Model ) ; 4 class Hello extends AppModel { 5 } 6?> app/model/hello.php 2 App : : uses ( AppController, Controller ) ; 4 class HellosController extends AppController { 5 6 function index ( ) { 7 } 8 } 9?> app/controller/helloscontroller.php Dr inż. Stanisław Polak 19 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 20 Przedmiot: Aplikacje internetowe
Lista użytkowników Przykłady Aplikacja Lista użytkowników Lista użytkowników Przykłady Schemat BD Mechanizm rusztowania Wymagane Model Kontroler $scaffold Modyfikowalne listy zawartości Założenia Podstawowe informacje o użytkowniku baza danych Funkcjonalność CRUD mechanizm rusztowania URL: http://localhost:8080/users/ 1 CREATE TABLE users ( 2 id integer PRIMARY KEY, username VARCHAR ( 8 ) NOT NULL UNIQUE, 4 password char (40), 5 imie VARCHAR (20), 6 nazwisko VARCHAR (20), 7 email VARCHAR ( 0 ) 8 ) ; Dr inż. Stanisław Polak 21 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 22 Przedmiot: Aplikacje internetowe Lista użytkowników Przykłady Kontroler Lista użytkowników Przykłady Model 2 App : : uses ( AppController, Controller ) ; 4 class UsersController extends AppController { 5 public $scaffold ; 6 } 7?> app/controller/userscontroller.php 2 App : : uses ( AppModel, Model ) ; 4 class User extends AppModel { 5 } 6?> app/model/user.php Dr inż. Stanisław Polak 2 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 24 Przedmiot: Aplikacje internetowe
Lista użytkowników Przykłady Aplikacja Generowanie kodu Przykłady Konsola CakePHP Generowanie aplikacji z poziomu linii komend 1 cake bake project /tmp/$user/httpd/htdocs/aplikacja 2 cd /tmp / $USER / httpd / htdocs / aplikacja sqlite BD. sqlite 4 #tworzymy odpowiednie t a b e l e w bazie danych 5... 6 cake bake db config 7 cake bake 8 cake bake model [nazwa modelu] 9 cake bake controller user 10 cake bake controller user --public 11 cake bake controller user --public --admin 12 cake bake view user class UsersController extends AppController { 4 ############################################# 5 #http : / / localhost :8080/ users / 6 public function index ( ) {... } 7 8 #http : / / localhost :8080/ users / view /1 9 public function view ( $id = null ) {... } 10... 11 ############################################# 12 1 #http : / / localhost :8080/ admin / users / 14 public function admin_index ( ) {... } 15 16 #http : / / localhost :8080/ admin / users / view /1 17 public function admin_view ( $id = null ) {... } 18 19 public function admin_add ( ) {... } 20 public function admin_edit ( $id = null ) {... } 21 public function admin_delete ( $id = null ) {... } 22 } Controller/UsersController.php 1 Configure : : write ( Routing. prefixes, array ( admin ) ) ; Config/core.php Dr inż. Stanisław Polak 25 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 26 Przedmiot: Aplikacje internetowe Kontroler Kontroler Wybrane atrybuty i metody Aplikacja Hello World Wersja zmodyfikowana class RecipesController extends AppController { 4 public $name = Recipes ; 5 # Katalog z widokami : app / View /$name/ 6 # Nazwa modelu : L i c z b a P o j e d y n c z a ( $name ) 7 8 public $uses = array ( Recipe, User ) ; 9 #p u b l i c $ u s e s = a r r a y ( ) ; 10 #p u b l i c $ u s e s = f a l s e ; 11 public $helpers = array ( Js => array ( Jquery ) ) ; 12 public $components = array ( Auth ) ; 1 14 function akcja ( ) { 15 $this >set( color, pink ) ; # W widoku j e s t dost ępna zmienna $color ; 16 $this >redirect( array ( controller => orders, action => confirm ) ) ; 17 $this >render( $view, $layout ) ; 18 } 19 } Poprzednia wersja class HellosController extends AppController { 4 5 function index ( ) { 6 } 7 } 8?> app/controller/helloscontroller.php 1 Hello World app/view/hellos/index.ctp Nowa wersja class HellosController extends AppController { 4 5 function index ( ) { 6 $this >set ( komunikat, Hello World ) ; 7 } 8 } 9?> app/controller/helloscontroller.php 2 echo $komunikat ;?> app/view/hellos/index.ctp Dr inż. Stanisław Polak 27 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 28 Przedmiot: Aplikacje internetowe
Kontroler Wybrane funkcje wywołań zwrotnych (callbacks) Komponenty Kontroler Dostępne komponenty Acl Funkcja beforefilter() beforerender() afterfilter() Auth Session RequestHandler Security Cookie 1 function beforefilter ( ) { 2 $this >Auth >authorize = array ( Controller ) ; 4 $this >Cookie >name = CookieMonster ; 5 $this >Cookie >time = 6 0 0 ; // or 1 hour 6 } Kontroler Paginator Dr inż. Stanisław Polak 29 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 0 Przedmiot: Aplikacje internetowe Komponenty Kontroler Komponent Auth Włączenie uwierzytelniania Komponenty Kontroler Komponent Auth Obsługa procedury logowania 2 App : : uses ( Controller, Controller ) ; 4 class AppController extends Controller { 5 public $components = array ( Session, Auth ) ; 6... 7 } app/controller/appcontroller.php http://localhost:8080/... http://localhost:8080/users/login 1 CREATE TABLE users ( 2 id integer INTEGER PRIMARY KEY, username varchar (50), 4 password char ( 4 0 ) 5 ) ; SQL 2 class UsersController extends AppController { public $components = array ( Session, Auth ) ; #Je ż e l i app / C o n t r o l l e r / A p p o n t r o l l e r. php n i e z a w i e r a t e j l i n i i 4 5 function login ( ) { 6 if ( $this >request >is ( post ) ) { 7 if ( $this >Auth >login ( ) ) 8 return $this >redirect ( $this >Auth > redirecturl ( ) ) ; 9 else 10 $this >Session >setflash ( Nieprawidłowy login lub has ło, default, array ( ), auth ) ; 11 } 12 } 1 function logout ( ) { 14 $this >redirect ( $this >Auth >logout ( ) ) ; 15 } 16 17 function beforefilter ( ) { 18 parent : : beforefilter ( ) ; 19 $this >Auth >allow( register ) ; 20 } 21 } app/controller/userscontroller.php 2 echo $this >Session >flash ( auth ) ; echo $this >Form >create ( User, array ( action => login ) ) ; 4 echo $this >Form >input ( username ) ; 5 echo $this >Form >input ( password ) ; 6 echo $this >Form >end ( Login ) ; 7 echo $this >Html >link ( " Rejestracja nowego uż ytkownika ", / users / register ) ; 8?> app/view/users/login.ctp Dr inż. Stanisław Polak 1 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 2 Przedmiot: Aplikacje internetowe
Komponenty Kontroler Model Tworzenie własnego komponentu Charakterystyka class MathComponent extends Component { 4 function sum ( $x, $y ){ 5 return $x+$y ; 6 } 7 // c a l l e d before C o n t r o l l e r : : b e f o r e F i l t e r ( ) 8 function initialize(&$controller, $settings = array ( ) ) {... } 9 // c a l l e d a f t e r C o n t r o l l e r : : b e f o r e F i l t e r ( ) 10 function startup(&$controller ) {... } 11 // c a l l e d a f t e r C o n t r o l l e r : : beforerender ( ) 12 function beforerender(&$controller ) {... } 1 // c a l l e d a f t e r C o n t r o l l e r : : r e n d e r ( ) 14 function shutdown(&$controller ) {... } 15 // c a l l e d before C o n t r o l l e r : : r e d i r e c t ( ) 16 function beforeredirect(&$controller, $url, $status=null, $exit=true ) {... } 17 }?> app/controller/component/mathcomponent.php class IndexesController extends AppController{ 4 public $components = array ( Math ) ; 5 function index ( ){ 6 $x = 5 ; 7 $y = 5 ; 8 $sum = $this >Math >sum ($x, $y ) ; 9 } 10 }?> app/controller/indexescontroller.php Dane Tabela BD Pliki Rekordy LDAP Zdarzenia ical Wiersze pliku CVS... Powiązania Dr inż. Stanisław Polak Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 4 Przedmiot: Aplikacje internetowe Model Model Posługiwanie się modelem Pola specjalne 2 App : : uses ( AppModel, Model ) ; 4 class Ingredient extends AppModel { 5 } app/model/ingredient.php 2 App : : uses ( AppController, Controller ) ; 4 class IngredientsController extends AppController { 5 public $uses = array ( Ingredient, User ) ; 6 7 function index ( ) { 8 $ingredients = $this->ingredient >find ( all ) ; 9 $this >set ( ingredients, $ingredients ) ; 10... 11 $users = $this->user >find ( all ) ; 1 1 $this >loadmodel( Group ) ; 14 $groups = $this->group >find ( all ) ; 15... 16 } 17 } app/controller/ingredientscontroller.php title name created modified Dr inż. Stanisław Polak 5 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 6 Przedmiot: Aplikacje internetowe
Łączenie modeli Model Łączenie modeli Łączenie modeli Model Przykład jeden do jeden jeden do wielu wiele do jednego wiele do wielu Przykład / Typ asocjacji Użytkownik posiada jeden profil User hasone Profile Użytkownik posiada wiele komentarzy User hasmany Comment Profil należy do użytkownika Profile belongsto User Lekarz posiada i należy do wielu pacjentów Physician hasandbelongstomany Patient Schemat profiles.user id comments.user id profiles.user id patients physicians.id, patients physicians.patient id, patients physicians.physician id class User extends AppModel { 4 public $hasone = Profile ; 5 public $hasmany = array ( 6 Comment => array ( 7 classname => Comment, 8 conditions => array ( Comment.approved => 1 ), 9 order => Comment. created DESC 10 ) 11 ) ; 1 1 $this->comment->jakasfunkcja() ; 14... 15 } 1 $this >User >Comment >jakasfunkcja ( ) ; app/model/user.php app/controller/userscontroller.php Dr inż. Stanisław Polak 7 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 8 Przedmiot: Aplikacje internetowe Łączenie modeli Model Przykład Lista drużyn Pobieranie danych Model Pobieranie danych 1 CREATE TABLE players ( 2 id INTEGER PRIMARY KEY, firstname VARCHAR ( 5 0 ) NOT NULL, 4 lastname VARCHAR ( 5 0 ) NOT NULL, 5 position VARCHAR ( 2 5 ) NOT NULL, 6 team_id INTEGER 7 ) ; 2 App : : uses ( AppModel, Model ) ; 4 class Player extends AppModel { 5 public $belongsto = Team ; 6 } 7?> app/model/player.php 1 CREATE TABLE teams ( 2 id INTEGER PRIMARY KEY, name VARCHAR ( 5 0 ) NOT NULL 4 ) ; 2 App : : uses ( AppModel, Model ) ; 4 class Team extends AppModel { 5 public $hasmany = Player ; 6 public $displayfield = name ; 7 } 8?> app/model/team.php query(string $zapytanie) find($typ, $parametry) $typ [ all, list, neighbors, count, threaded, first ] $parametry tablica: conditions => array( Model.pole => $danawartość), recursive => 1, fields => array( Model.pole1, Model.pole2 ), order => array( Model.created, Model.pole DESC ), group => array( Model.pole ), limit => n, page => n, callbacks => true findallby<nazwapola>(string $wartość) findby<nazwapola>(string $wartość) field(string $nazwa, array $warunki = null, $porządek=null) read($pola, $id) Model::$data Model::$id Dr inż. Stanisław Polak 9 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 40 Przedmiot: Aplikacje internetowe
Pobieranie danych Model Przykłady Zapisywanie danych Model Podstawowy format danych 2 $this >Post >find ( list, array ( fields => Post. title ) ) ; $this >Post >id = 2 ; 4 $neighbors = $this >Post >find ( neighbors ) ; 5 $this >Model >find ( all, $condition ) ; 6 $this >User >findallbylastname( Polak ) ; // User. l a s t n a m e = Polak 7 $this >Cake >findbyid (7) ; // Cake. i d = 7 8 $this >Picture >query( " SELECT * FROM pictures LIMIT 2;" ) ; 9 echo $model >field( name, array ( created < => date ( Y-m-d H:i:s ) ), created DESC ) ; 10 $allcategories = $this >Category >find ( threaded ) ; 11 $this >User >id =1; 12 $dane=$this >User >read ( ) ; 1... Kontroler 1 Array ( 2 [ NazwaModelu ] => Array ( [ nazwapola1 ] => wartosc 4 [ nazwapola2 ] => wartosc 5 ) 6 ) 2 if (! empty ($this->request->data) ) { // I f t h e form data can be v a l i d a t e d and s a v e d... 4 if ( $this >Comment >save ($this->request->data) ) { 5 // Set a s e s s i o n f l a s h message and r e d i r e c t. 6 $this >Session >setflash ( " Comment Saved!" ) ; 7 $this >redirect ( / comments ) ; 8 } 9 } 10... Kontroler Dr inż. Stanisław Polak 41 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 42 Przedmiot: Aplikacje internetowe Zapisywanie danych Model Wybrane metody Zapisywanie danych Model Przykład 1 Zapis danych modelu głównego User oraz stowarzyszonego Profile, za pomocą metody save() save(array $dane = null, boolean $walidacja = true, array $listapól = array()) save(array $dane = null, array $parametry = array()) create(array $dane = array()) savefield(string $nazwapola, string $wartośćpola, $walidacja = false) #$this->nazwamodelu->id = $id updateall(array $pola, array $warunki) saveall(array $dane = null, array $opcje = array()) nazwy opcji [validate, atomic, fieldlist] 2 if (! empty ( $this >request >data ) ) { // Możemy zapisa ć dane User s ą one przechowywane w $this >request >data [ User ] 4 $uzytkownik = $this >User >save ( $this >request >data ) ; 5 // Je ż e l i zapisano dane o uż ytkowniku, możemy dodać te informacje i zapisa ć P r o f i l 6 if (! empty ( $uzytkownik ) ) { 7 // I d e n t y f i k a t o r nowo utworzonego u ż y t k o w n i k a z n a j d u j e s i ę w $ t h i s >User >i d 8 $this >request >data [ Profile ] [ user_id ] = $this >User >id ; 9 // Poniewa ż User i P r o f i l e s ą po ł ą czone r e l a c j ą hasone P r o f i l e, możemy u z y s k a ć d o s t ę p do modelu P r o f i l e z poziomu modelu User 10 $this >User >Profile >save ( $this >request >data ) ; 11 } 12 } 1... app/controller/userscontroller.php Dr inż. Stanisław Polak 4 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 44 Przedmiot: Aplikacje internetowe
Zapisywanie danych Model Przykład 2 Zapis danych modelu głównego Company oraz stowarzyszonego Account, za pomocą metody saveall() Usuwanie danych Model Dostępne metody 1 echo $this >Form >create ( Company, array ( action => add ) ) ; 2 echo $this >Form >input ( Company. nazwa, array ( label => Nazwa firmy ) ) ; echo $this >Form >input ( Company.opis ) ; 4 echo $this >Form >input ( Company. lokalizacja ) ; 5 echo $this >Form >input ( Account.0. nazwa, array ( label => Nazwa konta ) ) ; 6 echo $this >Form >input ( Account.0. nazwauzytkownika ) ; 7 echo $this >Form >input ( Account.0. email ) ; 8 echo $this >Form >end ( Dodaj ) ; app/view/companies/add.ctp delete(int $id = null, boolean $kaskadowo = true) deleteall(mixed $warunki, $kaskadowo = true, $callbacki = false) 1 #: Company hasmany Account function add ( ) { 4 if (! empty ( $this >request >data ) ) { 5 $this >Company >saveall ( $this >request >data, array ( validate => first ) ) ; 6 } 7 } 8... app/controller/companiescontroller.php Dr inż. Stanisław Polak 45 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 46 Przedmiot: Aplikacje internetowe Inne zagadnienia Model Wybrane atrybuty class Example extends AppModel { 4 public $usedbconfig = alternatywna ; 5 public $usetable = false ; // Ten model nie korzysta z t a b e l i BD 6 public $tableprefix = alternate_ ; // bę dzie szuka ł alte rna te ex ampl es 7 public $primarykey = example_id ; // example id j e s t polem w BD 8 public $displayfield = username ; 9 public $recursive = 1 // warto ś ć domyś lna ; 10 public $order = array ( " Example. pole1 " => "asc ", " Example. pole2 " => "DESC " ) ; 11 print_r ( $this >data ) ; 12 public $_schema = array ( 1 imie => array ( 14 type => string, 15 length => 0 16 ), 17 nazwisko => array ( 18 type => string, 19 length => 0 20 ), 21 email => array ( 22 type => string, 2 length => 0 24 ), 25 message => array ( type => text ) 26 ) ; 27 public cachequeries = true ; 28 } app/model/example.php Inne zagadnienia Model Funkcje wywołań zwrotnych Funkcja beforefind(array $danezapytania) afterfind(array $wyniki,boolean $pierwotny=false) beforevalidate(array $opcje=array()) beforesave(array $opcje=array()) aftersave($utworzono) beforedelete(boolean $kaskadowo=true) afterdelete() onerror() 2 App : : uses ( AuthComponent, Controller / Component ) ; 4 class User extends AppModel { 5 function beforesave ( $options = array ( ) ) { 6 $this >data [ User ] [ password ] = AuthComponent : : password ( $this >data [ User ] [ password ] ) ; 7 return true ; 8 } 9 } app/model/user.php Dr inż. Stanisław Polak 47 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 48 Przedmiot: Aplikacje internetowe
Inne zagadnienia Model Wirtualne pola 2 // Dla SQLite public $virtualfields = array ( 4 // Dla SQLite 5 nazwa => User. imie \ \ User. nazwisko 6 // Dla MySQL 7 // nazwa => CONCAT( User. imie,, User. n a z w i s k o ) 8 ) ; 9... app/model/user.php 2 $results = $this >User >find( first ) ; 4 // wynik zawiera nast ępujące dane 5 array ( 6 User => array ( 7 imie => Stanis ław, 8 nazwisko => Polak, 9 nazwa => Stanisław Polak, 10 // wi ę c e j pó l. 11 ) 12 ) ; 1 14 $this >User >hasfield ( nazwa ) ; // Zwraca false, gdy nie i s t n i e j e konkretne ( fizyczne ) pole o nazwie nazwa 15 $this >User >hasfield ( nazwa, true ) ; // Zwraca true, gdy i s t n i e j e wirtualne pole o nazwie nazwa 16 $this >User >isvirtualfield ( nazwa ) ; // t r u e 17 $this >User >isvirtualfield ( imie ) ; // f a l s e 18 $this >User >getvirtualfield ( nazwa ) ; // dla MySQL zwraca CONCAT( User. imie,, User. nazwisko ) 19... app/controller/userscontroller.php Inne zagadnienia Model Zarządzanie schematem bazy danych oraz migawki 1 cake schema generate 2 cake schema create cake schema update 4 cake schema update -s 2 #app / Config /Schema/ schema 2. php 5 cake schema dump --write dump.sql 1 class AplikacjaSchema extends CakeSchema { public $users = array ( 4 id => array ( type => integer, null => false, length => 11, key => primary ), 5 username => array ( type => string, null => false, length => 8), 6 password => array ( type => string, null => true, length => 40), 7 imie => array ( type => string, null => true, length => 20), 8 nazwisko => array ( type => string, null => true, length => 20), 9 email => array ( type => string, null => true, length => 0), 10 indexes => array ( 11 PRIMARY => array ( column => username, unique => 1) 12 ), 1 tableparameters => array ( ) 14 ) ; 15 } app/config/schema/schema.php Dr inż. Stanisław Polak 49 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 50 Przedmiot: Aplikacje internetowe Walidacja Model Reguły proste class User extends AppModel { 4 public $validate = array ( 5 login => alphanumeric, 6 email => email, 7 dataurodzenia => date 8 ) ; 9 } app/model/user.php Walidacja Model Reguły złożone class User extends AppModel { 4 public $validate = array ( 5 login => array ( 6 alfanumeryczne => array ( 7 rule => alphanumeric, 8 required => true, 9 message => Tylko litery lub cyfry 10 ), 11 pomiedzy => array ( 12 rule => array ( between, 5, 15), 1 message => Od 5 do 15 znak ów 14 ) 15 ), 16 password => array ( 17 rule => array ( minlength, 8 ), 18 message => Mimimum 8 znak ów 19 ), 20 email => email, 21 dataurodzenia => array ( 22 rule => date, 2 message => Podaj poprawn ą dat ę, 24 allowempty => true 25 ) 26 ) ; 27 } app/model/user.php Dr inż. Stanisław Polak 51 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 52 Przedmiot: Aplikacje internetowe
Walidacja Model Definiowanie własnych reguł 2 public $validate = array ( login => array ( 4 rule => /^[a-z0-9]{,} $/i, 5 message => Tylko cyfry lub litery, min. znaki 6 ) 7 ) ; 8... Użycie wyrażenia regularnego class User extends AppModel { 4 public $validate = array ( 5 promotion_code => array ( 6 rule => array ( limitduplicates, 25), 7 message => Przekroczono limit krotno ści uż ycia kodu. 8 ) 9 ) ; 10 function limitduplicates ( $data, $limit ){ 11 $existing_promo_count = $this >find ( count, array ( conditions => $data, recursive => 1) ) ; 12 return $existing_promo_count < $limit ; 1 } 14 } Własna metoda walidująca Zachowania Model Zachowania class Category extends AppModel { 4 public $actsas = array ( 5 Tree => array ( 6 left => left_node, 7 right => right_node 8 ), 9 Translate 10 ) ; 11 } app/model/category.php class CategoriesController extends AppController { 4 5 public function index ( ) { 6 this >Category >id = 4 2 ; 7 kids = $this >Category >children ( ) ; 8 this >Category >Behaviors >unload ( Translate ) ; 9 this >Category >Behaviors >load ( Tree, array ( left => new_left_node ) ) ; 10 } 11 } app/controller/categoriescontroller.php Dr inż. Stanisław Polak 5 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 54 Przedmiot: Aplikacje internetowe Zachowania Model Widok Dostępne zachowania Składniki warstwy widoku ACL Containable Translate Tree Widoki (Views) Układy (Layouts) Elementy (Elements) Pomocnicy (Helpers) Motywy (Themes) app webroot View Themed... NazwaKontrolera NazwaMotywu webroot... NazwaKontrolera Dr inż. Stanisław Polak 55 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 56 Przedmiot: Aplikacje internetowe
Składniki warstwy widoku Widok Widoki Składniki warstwy widoku Widok Układy 1 <div class=" logout "><a href="/ users / logout "><img src="/ img / logout. png " width="0" alt="[ logout ]">Wylogowanie</a></div> 2 <aside> <h1>menu</h1> 4 <div> 5 <h2>panele</h2> 6 <ul> 7 <?php echo $this >fetch( panels ) ;?> 8 </ul> 9 </div> 10 </aside> 11 12 <h2><?php echo $this >fetch( title ) ;?></h2> 1 <?php echo $this >fetch( content ) ;?> 14 <div class=" logout "><a href="/ users / logout "><img src="/ img / logout. png " width="0" alt="[ logout ]">Wylogowanie</a></div> app/view/people/common/main.ctp 2 // Pozosta ł a zawarto ść staje s i ę tre ś ci ą bloku o nazwie c o n t e n t $this >extend( Common/main ) ; 4 $this >assign( title, Panel użytkownika ) ; 5 //Utwó rz blok panels 6 $this >start( panels ) ; 7 echo <li><a href="/notes ">Notek </a></li> ; 8 echo <li ><a href ="/ users "> Administratora </a > </ li > ; 9 $this >end() ;?> 10 11 // Pozosta ł a zawarto ść staje s i ę tre ś ci ą bloku o nazwie c o n t e n t 12 Treść app/view/people/index.ctp 1 <!DOCTYPE html> 2 <html lang="en"> <head> 4 <?php echo $this >Html >charset ( ) ;?> 5 <title><?php echo $title for layout;?></title> 6 <link rel=" shortcut icon " href=" favicon. ico " type=" image /x- icon "> 7 <?php 8 echo $this->fetch( meta ); 9 echo $this->fetch( css ); 10 echo $this->fetch( script );?> 11 </head> 12 <body> 1 <?php echo $this->fetch( content );?> 14 </body> 15 </html> app/view/layouts/uklad.ctp class PeopleController extends AppController { 4 function index ( ) { 5... 6 // Poniż sze l i n i e można również umieś ci ć w pliku widoku 7 $this->set( title_for_layout, Panel u ż ytkownika ); 8 $this->layout = uklad ; 9... 10 } 11 } app/controller/peoplecontroller.php Dr inż. Stanisław Polak 57 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 58 Przedmiot: Aplikacje internetowe Składniki warstwy widoku Widok Pomocnicy Składniki warstwy widoku Widok Podstawowi pomocnicy class PeopleController extends AppController { 4 public $helpers = array ( Form, Time ) ; 5... 6 function akcja ( ) { 7 $this->helpers[] = Number ; 8 } 9... 10 } Pomocnik Pomocnik Pomocnik Pomocnik Cache Form Html Js Number Paginator Rss Session Text Time app/controller/peoplecontroller.php Dr inż. Stanisław Polak 59 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 60 Przedmiot: Aplikacje internetowe
Składniki warstwy widoku Widok Pomocnik Paginator class UsersController extends AppController { 4 public $components=array ( Paginator ) ; 5 public $helpers=array ( Paginator ) ; 6 7 function index ( ) { 8 $this >Paginator >settings = array ( limit => 2, page => 1) ; 9 $this >set ( users, $this >Paginator >paginate ( ) ) ; 10 } 11 } app/controller/userscontroller.php 1 <table cellpadding="0" cellspacing="0"> 2 <tr> <th><?php echo $this >Paginator >sort( id ) ;?></th> 4... 5 </tr> 6 <?php foreach ( $users as $user ) :?> 7 <tr> 8 <td><?php echo $user [ User ] [ id ] ;?></td> 9... 10 </tr> 1 endforeach ;?> 12 </table> 1 <?php 14 echo $this >Paginator >counter ( array ( 15 format => Page {: page } of {: pages }, showing {: current } records out of {: count } total, starting on record {: start }, ending on {: end } 16 ) ) ; 17 echo $this >Paginator >prev( <previous ), array ( ), null, array ( class => prev disabled ) ) ; 18 echo $this >Paginator >numbers(array ( separator => ) ) ; 19 echo $this >Paginator >next( next >, array ( ), null, array ( class => next disabled ) ) ; 20?> app/view/users/index.ctp Składniki warstwy widoku Widok Tworzenie pomocnika Przykład 2 App : : uses ( AppHelper, View / Helper ) ; 4 class LinkHelper extends AppHelper { 5 public $helpers = array ( Html ) ; 6 7 function link ( $create, $title, $url ){ 8 if ( $create ) 9 return $this >Html >link ( $title, $url ) ; 10 else 11 return $title ; 12 } 1 } app/view/helper/linkhelper.php 2 <?php echo $this >Link->link( $notespanel, Notek, / notes )?>... class PeopleController extends AppController { 4 public $helpers = array ( Link ) ; 5 6 public function index ( ){ 7... 8 // Sprawd ź czy i s t n i e j e k o n t r o l e r Notes 9 $notespanel = App : : import ( Controller, Notes ) ; // t r u e, j e ś l i k l a s a jest ju ż w pamię ci lub je ś l i plik z o s t a ł z n a l e z i o n y i za ł adowany ; f a l s e j e ś l i n i e 10 $this >set ( notespanel, $notespanel ) ; 1 12 } 1 } app/view/people/index.ctp app/controllers/peoplecontroller.php Dr inż. Stanisław Polak 61 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 62 Przedmiot: Aplikacje internetowe Składniki warstwy widoku Widok Klasy wspomagające Elementy Funkcjonalności 2 echo $this >element( logout ) ; echo $this >element( logout, 4 array ( 5 "text" => " Wylogowanie " 6 ), 7 array ( 8 "cache" => true, 9 "callbacks" => true #Funkcje zwrotne beforerender oraz afterrender będą uruchamiane 10 ) 11 ) ; Widok 2 $content =! empty ($text)? $text : Wylogowanie ;?> 4 <div class=" logout "><a href="/ users / logout "><img src="/img / logout.png " width="0 " alt="[ logout ]"><?php echo $content ;?></a></div> app/view/elements/logout.ctp Dziennikowanie Buforowanie Umiędzynarodowienie i lokalizacja Operacje tablicowe Operacje łańcuchowe Tworzenie obiektów SimpleXml lub DOMDocument Odmiana wyrazów Gniazda (sockety) HTTP Parsowanie URL Haszowanie i szyfrowanie Oczyszczanie danych Poczta Katalogi i pliki Dostęp do funkcjonalności pomocników Time, Number oraz Text Dr inż. Stanisław Polak 6 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 64 Przedmiot: Aplikacje internetowe
Klasy wspomagające Lokalizacja i umiędzynarodowienie Klasy wspomagające Oczyszczanie danych Wyświetlanie tekstu wielojęzycznego 2 App : : uses( Sanitize, Utility ) ;... 4 $badstring = ";: < script ><html >< // >@@#" ; 5 echo Sanitize : : paranoid( $badstring ) ; // na wyj ś c i u : s c r i p t h t m l 6 echo Sanitize : : paranoid( $badstring, array (, @ ) ) ; // na wyj ś c i u : s c r i p t h t m l @@ 7 $badstring = <font size ="99" color="# FF0000 ">HEY </ font ><script >... </ script > ; 8 echo Sanitize : : html( $badstring ) ; // na wyj ś c i u : & l t ; f o n t s i z e=" ;99& quot ; c o l o r =" ;#FF0000" ;& gt ; HEY& l t ; / f o n t> ;& l t ; s c r i p t> ;... & l t ; / s c r i p t> ; 9 #zak ł adamy, ż e w t a b l i c y $ o p c j e k l u c z remove w s k a z u j e warto ś ć TRUE 10 echo Sanitize : : html( $badstring, $opcje ) ; // na wyj ś c i u : HEY... 11 echo Sanitize : : escape( " Stanislaw Polak s page ", default ) ; // na wyj ś ciu : Stanislaw Polak s page 12 Sanitize : : clean( $this >request >data, array ( encode => false ) ) ; 1... Przykłady użycia Pojęcia podstawowe Umiędzynarodowienie (i18n) Lokalizacja (l10n) Globalizacja (g11n) = i18n + l10n Przygotowanie danych 1 msgid " first name " 2 msgstr " First name " msgid " message " 4 msgstr " You belong to a group of %s " app/locale/eng/lc MESSAGES/default.po 1 msgid " first name " 2 msgstr " Imi ę" msgid " message " 4 msgstr " Nale ż ysz do grupy %s " app/locale/pol/lc MESSAGES/default.po Przykład użycia 1 echo ( " first name " ) }; 2 echo ( message, $dane [ Group ] [ name ] ) ; Widok 2 Configure : : write ( Config. language, pol ) ;... Kontroler Dr inż. Stanisław Polak 65 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 66 Przedmiot: Aplikacje internetowe Lokalizacja i umiędzynarodowienie Klasy wspomagające Kontrola dostępu (ACL) Tłumaczenie rekordów bazy danych Podstawowe pojęcia cake i18n 1 CREATE TABLE notes ( 2 id integer PRIMARY KEY, title varchar ( 2 5 5 ) default NULL, 4 body text 5 ) ; SQL 2 public $actsas = array ( Translate => array ( title, body ) ) ;... app/model/note.php ACL (Access Control List) określa kto ma dostęp do czego ARO (Access Request Object) reprezentuje kto ACO (Access Control Object) reprezentuje czego 2 function beforefilter ( ) { Configure : : write ( Config. language, pol ) ; 4 } 5... app/controller/notescontroller.php Dr inż. Stanisław Polak 67 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 68 Przedmiot: Aplikacje internetowe
Kontrola dostępu (ACL) Tabele z informacjami o użytkownikach Autoryzatory Kontrola dostępu (ACL) Dostępne autoryzatory 1 CREATE TABLE users ( 2 id INTEGER PRIMARY KEY, username CHAR ( 8 ) NOT NULL UNIQUE, 4 password CHAR ( 4 0 ) NOT NULL, 5 group_id TINYINT NOT NULL, 6... 7 ) ; 8 9 CREATE TABLE groups ( 10 id INTEGER PRIMARY KEY, 11 name VARCHAR ( 2 0 ) NOT NULL, 1 1 ) ; 14... ActionsAuthorize CrudAuthorize ControllerAuthorize SQL Dr inż. Stanisław Polak 69 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 70 Przedmiot: Aplikacje internetowe Autoryzatory Kontrola dostępu (ACL) Autoryzator ActionsAuthorize Autoryzatory Kontrola dostępu (ACL) Autoryzator CrudAuthorize 2 class AppController extends Controller {... 4 public $components = array ( 5 Acl, 6 Auth => array ( 7 authorize => array ( Actions => array ( actionpath => controllers / ) ) 8 ), 9... 10 ) ; 1 12 } app/controller/appcontroller.php class AppController extends Controller { 4 public $components = array ( 5 Acl, 6 Auth => array ( 7 authorize => array ( 8 Crud => array ( 9 / 10 i n d e x => r e a d, 11 add => c r e a t e, 12 e d i t => update, 1 view => r e a d, 14 remove => d e l e t e, 15 c r e a t e => c r e a t e, 16 r e a d => r e a d, 17 update => update, 18 d e l e t e => d e l e t e 19 / 20 actionmap => array ( show => read, pokaz => read ) 21 ) 22 ) 2 ) 24 ) ; 25... 26 } app/controller/appcontroller.php 2 function beforefilter ( ) { parent : : beforefilter ( ) ; 4 $this >Auth >mapactions( 5 array ( 6 create => array ( register, dodaj ), 7 read => array ( wyswietl ) 8 ) 9 ) ; 10 } 1 Kontroler Dr inż. Stanisław Polak 71 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 72 Przedmiot: Aplikacje internetowe
Autoryzatory Kontrola dostępu (ACL) Autoryzator ControllerAuthorize Implementacje Kontrola dostępu (ACL) Dostępne implementacje ACL 2 class UsersController extends Controller { public $components = array ( 4 Auth => array ( authorize => Controller ), 5 ) ; 6 7 public function isauthorized( $user = null ) { 8 $usergroup = $user [ Group ] [ name ] ; 9 10 // A d m i n i s t r a t o r z y mogą wykonywa ć dowolne a k c j e k o n t r o l e r a Users, p o z o s t a l i ty lk o akcje index oraz view 11 if ( $usergroup == administrators in_array ( $this >action, array ( index, view ) ) ) { 12 return true ; // zezwolenie na dost ęp do zasobu 1 } 14 15 if ( $usergroup == users ) { 16 return false ; // brak prawa dost ępu do zasobu 17 } 18 return false ; 19 } 20 } app/controller/userscontroller.php IniAcl PhpACl DbAcl Dr inż. Stanisław Polak 7 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 74 Przedmiot: Aplikacje internetowe Implementacje Kontrola dostępu (ACL) Implementacja IniAcl Implementacje Kontrola dostępu (ACL) Implementacja PhpAcl 1 Configure : : write ( Acl. classname, IniAcl ) ; 2 #C o n f i g u r e : : w r i t e ( Acl. d a t a b a s e, d e f a u l t ) ; app/config/core.php 2 class AppController extends Controller { public $components = array ( 4 Acl, 5 Auth => array ( 6 authorize => array ( Actions => array ( actionpath => controllers / ) ) 7 ), 8... 9 ) ; 10... 11 } app/controller/appcontroller.php 1 ; 2 ; Users ; 4 5 [ polak ] 6 groups = administrators 7 allow = 8 deny = 9 10 [ user ] 11 groups = users 12 allow = 1 deny = 14 15 ; 16 ; Groups 17 ; 18 19 [ users ] 20 allow = controllers / People / index 21 deny = 22 2 [ administrators ] 24 allow = controllers / People /index, controllers / Users / index,... 25 deny = app/config/acl.ini.php 1 Configure : : write ( Acl. classname, PhpAcl ) ; 2 #C o n f i g u r e : : w r i t e ( Acl. d a t a b a s e, d e f a u l t ) ; app/config/core.php 2 class AppController extends Controller { public $components = array ( 4 Acl, 5 Auth => array ( 6 authorize => array ( Actions => array ( actionpath => controllers / ) ) 7 ), 8... 9 ) ; 10... 11 } app/controller/appcontroller.php 1 $config [ map ] = array ( 2 User => User / username, Role => User / group_id, 4 ) ; 5 $config [ alias ] = array ( 6 Role /1 => Role / user, 7 Role /2 => Role / staff, 8 Role / => Role / admin 9 ) ; 10 $config [ roles ] = array ( 11 Role / user => null, 12 Role / staff => null, 1 Role / admin => null, 14 Role / editor => Role /user, Role / staff, 15 User / polak => Role / editor, 16 ) ; 17 $config [ rules ] = array ( 18 allow => array ( 19 * => Role / admin, 20 controllers / Pages / display => Role / default, Role / user, 21 controllers / Users /( index view ) => Role / user, 2 2 ), 24 deny => array ( 25 controllers / Users / delete => Role / editor, 26... 27 ), 28 ) ; app/config/acl.php Dr inż. Stanisław Polak 75 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 76 Przedmiot: Aplikacje internetowe
Implementacje Kontrola dostępu (ACL) Implementacja DbAcl 1 Configure : : write ( Acl. classname, DbAcl ) ; 2 Configure : : write ( Acl. database, default ) ; app/config/core.php 2 class AppController extends Controller { public $components = array ( 4 Acl, 5 Auth => array ( 6 authorize => array ( Actions => array ( actionpath => controllers / ) ) 7 ), 8... 9 ) ; 10... 11 } app/controller/appcontroller.php Tworzenie tabel ACL cake acl initdb 1 CREATE TABLE " aros " ( 2 "id" integer primary key autoincrement, " parent_id " integer ( 1 0 ) DEFAULT NULL, 4 " model " varchar ( 2 5 5 ) DEFAULT NULL, 5 " foreign_key " integer ( 1 0 ) DEFAULT NULL, 6 " alias " varchar ( 2 5 5 ) DEFAULT NULL, 7 " lft " integer ( 1 0 ) DEFAULT NULL, 8 " rght " integer ( 1 0 ) DEFAULT NULL 9 ) ; 10 11 CREATE TABLE " acos " ( 12 "id" integer primary key autoincrement, 1 " parent_id " integer ( 1 0 ) DEFAULT NULL, 14 " model " varchar ( 2 5 5 ) DEFAULT NULL, 15 " foreign_key " integer ( 1 0 ) DEFAULT NULL, 16 " alias " varchar ( 2 5 5 ) DEFAULT NULL, 17 " lft " integer ( 1 0 ) DEFAULT NULL, 18 " rght " integer ( 1 0 ) DEFAULT NULL 19 ) ; 20 21 22 CREATE TABLE " aros_acos " ( 2 "id" integer primary key autoincrement, 24 " aro_id " integer ( 1 0 ) NOT NULL, 25 " aco_id " integer ( 1 0 ) NOT NULL, 26 " _create " varchar ( 2 ) DEFAULT 0 NOT NULL, 27 " _read " varchar ( 2 ) DEFAULT 0 NOT NULL, 28 " _update " varchar ( 2 ) DEFAULT 0 NOT NULL, 29 " _delete " varchar ( 2 ) DEFAULT 0 NOT NULL 0 ) ; SQL Implementacje Kontrola dostępu (ACL) Implementacja DbAcl Automatyczne dodawanie/usuwanie ARO podczas dodawania/usuwania użytkownika lub grupy class User extends Model { 4 public $belongsto = array ( Group ) ; 5 public $actsas = array ( Acl => array ( type => requester ) ) ; 6 7 function parentnode() { 8 if (! $this >id && empty ( $this >data ) ) { 9 return null ; 10 } 11 if ( isset ( $this >data [ User ] [ group_id ] ) ) { 12 $groupid = $this >data [ User ] [ group_id ] ; 1 } else { 14 $groupid = $this >field ( group_id ) ; 15 } 16 if (! $groupid ) { 17 return null ; 18 } else { 19 return array ( Group => array ( id => $groupid ) ) ; 20 } 21 } 22 } app/model/user.php class Group extends Model { 4 public $hasmany = array ( User ) ; 5 public $actsas = array ( Acl => array ( type => requester ) ) ; 6 7 function parentnode() { 8 return null ; 9 } 10 } app/model/group.php Dr inż. Stanisław Polak 77 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 78 Przedmiot: Aplikacje internetowe Implementacje Kontrola dostępu (ACL) Implementacja DbAcl Tworzenie ARO Implementacje Kontrola dostępu (ACL) Implementacja DbAcl Tworzenie ACO 1 cake acl create aro root Group. 1 2 cake acl create aro root Group. 2 cake acl create aro root Group. 4 5 cake acl create aro Group. 1 User. 6 cake acl create aro Group. 2 User. 2 7 cake acl create aro Group. User. 1 Tworzenie, przy użyciu skryptu cake 1 cake acl view aro 2 Welcome to CakePHP v2.. 4 Console 4 5 App : aplikacja 6 Path : / home / polak / aplikacja / 7 8 Aro tree : 9 10 [ 1 ] Group. 1 11 [ 4 ] User. 12 [ 2 ] Group. 2 1 [ 5 ] User.2 14 [ ] Group. 15 [ 6 ] User.1 16 Wyświetlenie drzewa ARO 1 $aro = $this >Acl >Aro ; 2 $groups = array ( 0 => array ( 4 alias => Group.1, 5 model => Group, 6 foreign_key => 1 # id grupy z t a b e l i groups 7 ), 8 1 =>..., 9 2 =>... 10 ) ; 11 foreach ( $groups as $data ) { 12 $aro >create ( ) ; 1 $aro >save ( $data ) ; 14 } 15 ############################### 16 $aro = new Aro ( ) ; 17 $users = array ( 18 0 => array ( 19 alias => User., 20 parent_id => 1, # id węz ł a w drzewie ARO, tu ; id węz ł a o nazwie Group.1 21 model => User, 22 foreign_key =>, # id uż ytkownika z tabeli users 2 ), 24 1 =>..., 25 2 =>... 26 ) ; 27 foreach ( $users as $data ) { 28 $aro >create ( ) ; 29 $aro >save ( $data ) ; 0 } Z poziomu kontrolera 1 cake acl create aco root controllers 2 cake acl create aco controllers Users cake acl create aco controllers / Users create 4... Za pomocą skryptu cake 1 $aco =& $this >Acl >Aco ; 2 $aco >create ( array ( parent_id => null, alias => controllers ) ) ; $root = $aco >save ( ) ; 4 $controllers_id = $root [ Aco ] [ id ] ; 5 $aco >create ( array ( parent_id => $controllers_id, alias => Users ) ) ; 6 $root = $aco >save ( ) ; 7 $users_id = $root [ Aco ] [ id ] ; 8 $aco >create ( array ( parent_id => $users_id, alias => create ) ) ; 9 $aco >save ( ) ; 10... Z poziomu kontrolera Dr inż. Stanisław Polak 79 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 80 Przedmiot: Aplikacje internetowe
Implementacje Kontrola dostępu (ACL) Implementacja DbAcl Tworzenie powiązań pomiędzy ARO a ACO Testowanie Rama testująca PHPUnit Programowanie sterowane testami Tworzenie i wykonywanie testów jednostkowych Instalacja 1 cake acl grant Group. controllers all 2 cake acl grant Group. 2 controllers / Notes all cake acl grant Group. 1 controllers / People read Za pomocą skryptu cake 2 $group = $this >User >Group ; //Uż ytkownicy z grupy mogą wykonywać dowolne ( w s z y s t k i e ) a k c j e 4 $group >id = ; 5 $this >Acl >allow ( $group, controllers ) ; 6 7 //Uż ytkownicy z grupy 2 mogą wykonywać dowolne akcje dla k o n t r o l e r a Notes 8 $group >id = 2 ; 9 $this >Acl >deny ( $group, controllers ) ; 10 $this >Acl >allow ( $group, controllers / Notes ) ; 11 12 //Uż ytkownicy z grupy 1 mogą wykonywać akcje typu r e a d d l a k o n t r o l e r a People 1 $group >id = 1 ; 14 $this >Acl >deny ( $group, controllers ) ; 15 $this >Acl >allow ( $group, controllers / People, read ) ; Z poziomu kontrolera 1 pear upgrade PEAR 2 pear config set auto_discover 1 pear install pear. phpunit. de/ PHPUnit Konfigurowanie CakePHP 1 Configure : : write ( debug, 1) ; #Warto ś ć parametru debug 1 1 public $test = array ( 2 datasource =>...,... 4 ) ; app/config/core.php app/config/database.php Etapy procedury testowania 1. Opcjonalnie, utworzenie osprzętu testowania (fixture) 2. Utworzenie testów. Uruchomienie testów Dr inż. Stanisław Polak 81 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 82 Przedmiot: Aplikacje internetowe Osprzęt testowania Programowanie sterowane testami Tworzenie osprzętu testowania Osprzęt testowania Programowanie sterowane testami Importowanie definicji i rekordów 2 class UserFixture extends CakeTestFixture { public $fields = array ( 4 id => array ( type => integer, null => false, length => 11, key => primary ), 5 username => array ( type => string, null => false, length => 50), 6 password => array ( type => string, null => true, length => 40), 7 group_id => array ( type => integer, null => true ), 8 indexes => array ( PRIMARY => array ( column => username, unique => 1) ), 9 tableparameters => array ( ) 10 ) ; 11 12 public $records = array ( 1 array ( 14 id => 1, 15 username => admin, 16 password => 42488 fc1ca166055a25701d12f14f0fd74ba50, 17 group_id => 1 18 ), 19 array ( 20 id => 2, 21 username => manager, 22 password => 8951 d5c5c26e451a6a76c55e950d65fd2e145, 2 group_id => 2 24 ) 25 ) ; 26 } 2 class UserFixture extends CakeTestFixture { public $import = User ; 4 public $import = array ( model => User, records => true ) ; 5 public $import = array ( table => users ) ; 6 public $import = array ( table => users, records => true ) ; 7 } app/test/fixture/userfixture.php app/test/fixture/userfixture.php Dr inż. Stanisław Polak 8 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 84 Przedmiot: Aplikacje internetowe
Testy Programowanie sterowane testami Co można testować Testy Programowanie sterowane testami Reguły dla testów Katalog app/test/case/[typ] Modele Kontrolery Pomocnicy Komponenty Nazwy plików *Test.php Klasy nadrzędne CakeTestCase i ControllerTestCase PHPUnit Framework TestCase Nazwy metod zawierających testy admins() testadmins() Dr inż. Stanisław Polak 85 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 86 Przedmiot: Aplikacje internetowe Testy Programowanie sterowane testami Testowanie modeli class User extends AppModel { 4 function admins( $fields = null ) { 5 $params = array ( 6 conditions => array ( 7 $this >name.. group_id => 8 ), 9 fields => $fields 10 ) ; 11 return $this >find ( all, $params ) ; 12 } 1 } app/model/user.php 2 App : : uses ( User, Model ) ; 4 class UserTestCase extends CakeTestCase { 5 public $fixtures = array ( app. user, app. group, app. profile ) ; 6 7 public function setup() { 8 parent : : setup ( ) ; 9 $this >User = ClassRegistry : : init ( User ) ; 10 } 11 12 public function teardown() { 1 unset ( $this >User ) ; 14 parent : : teardown ( ) ; 15 } 16 17 function testadmins() { 18 $result = $this >User > admins( array ( username ) ) ; 19 $expected = array ( 20 array ( User => array ( username => admin1 ) ), 21 array ( User => array ( username => admin2 ) ) 22 ) ; 2 24 $this >assertequals($expected, $result) ; 25 } 26 } app/test/case/model/usertest.php Uruchamianie testów Programowanie sterowane testami Sposoby uruchomienia testów Testowanie przykładowego modelu User Pierwszy sposób 1. DEBUG 1 2. http://localhost:8080/test.php. App / Tests 4. Model / User Drugi sposób cake test app/model/user.php --stderr Dr inż. Stanisław Polak 87 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 88 Przedmiot: Aplikacje internetowe
Źródła Źródła Źródła I Źródła II Faheem Abbas. Defining your own components in cakephp. http://zendguru.wordpress.com/2009/01/01/ defining-your-own-components-in-cakephp/. the bakery. http://bakery.cakephp.org/. Dokumentacja CakePHP. http://book.cakephp.org/2.0/en/. Jason Gilmore. Scaffolding with cakephp - managing your fantasy football team. http://www.developer.com/lang/php/article.php/66686. Maciej Grajcarek. L10n i i18n w cakephp 1.2. http: //blog.uplevel.pl/index.php/2008/05/l10n-i-i18n-w-cakephp-12/. Matt Inman. 21 things you must know about cakephp. http://cake-php.blogspot.com/2006/09/ 21-things-you-must-know-about-cakephp.html. Wikipedia. http://pl.wikipedia.org/. Dr inż. Stanisław Polak 89 Przedmiot: Aplikacje internetowe Dr inż. Stanisław Polak 90 Przedmiot: Aplikacje internetowe