100
Zend Framework Day 1

Zend

Embed Size (px)

Citation preview

Page 1: Zend

Zend Framework

Day 1

Page 2: Zend

Agenda

● History ● Download and installation ● Create and Configure Your First Zend Project● MVC● Zend Model● Zend Controller● Zend Action● Zend View● Zend Layout● Lab Time

Page 3: Zend

History

● Coding on Zend Framework officially started in July 2005.● The first public release was on March 4, 2006, version 0.1.2.● More than a year later, the first version (1.0) was released on July 2,

2007.● Initial development of Zend Framework 2.0 was released on August 6,

2010.● The first stable release of Zend Framework 2.0 was released 5

September, 2012.

Page 4: Zend

More About Zend

● Free and open source framework● Extreme Simplicity● Flexible Architecture● Support for multiple database systems and vendors,

including MariaDB MySQL, Oracle, IBM DB2, Microsoft SQL Server, PostgreSQL,SQLite, and Informix Dynamic Server.

Page 5: Zend

MVC

Model - The part of your application that defines its basic functionality. Data access routines and some business logic can be defined in the model.

View - Views define exactly what is presented to the user. Usually controllers pass data to each view to render in some format. Views will often collect data from the user, as well. This is where you're likely to find HTML.

Controller - Controllers bind the whole pattern together. They manipulate models, decide which view to display based on the user's request and other factors, pass along the data that each view will need, or hand off control to

Page 6: Zend

The Flow

A model Class talks with the DB, perform whatever logic needed and return it to the controller action . The Controller Action get and send data from and to the view and talk to model to get the needed logic . The View send and receives data to and from the involved controller action.

Page 7: Zend

Pre-Requests

1- Apache2 web server 2- MySQL DB Server

Test it by: sudo service apache2 restart If okay then okay .. else run those sequentially:

Sudo apt-get --purge remove apache2

Sudo apt-get autoremove

Sudo apt-get install apache2

Sudo /etc/init.d/apache2 restart And test it by navigating the browser to loaclhost sudo tasksel install lamp-server is an option too

Page 8: Zend

DownLoad & Installation

● Download the latest version of Zend Framework 1.0 from this link

http://framework.zend.com/downloads/latest#ZF1

● Extract the downloaded file to your localhost directory.

/var/www/html

Page 9: Zend

Download & Installation

● We use Zend Tool to create projects, controllers, models, …. ● In order to can use Zend command line tool we need to configure it :

○ Sudo gedit ~/.bashrc

○ Add these two lines:■ PATH=$PATH:/var/www/html/ZendFramework-1.12.1/bin/■ alias zf="/var/www/html/ZendFramework-1.12.1/bin/zf.sh"

○ Add permission execute at localhost directory:

■ Sudo chmod +x /var/www/html

Now we have Zend Command line tool “ ZF ”

Page 10: Zend

Create Zend Project

Four Steps:

1. Create project

zf create project /var/www/html/project_name

Page 11: Zend

Create Zend Project

2. Create a symbolic link of the Zend framework into project libraries

ln –s /var/www/html/ZendFramework-1.12.1/library/Zend

/var/www/html/project_name/library

Page 12: Zend

Create Zend Project

3. Define the project into the web server [Apache2]

○ sudo gedit /etc/apache2/apache2.conf

○ Add these: <Directory /var/www/html/project_name >DirectoryIndex index.phpAllowOverride All</Directory>

○ sudo a2enmod rewrite #a2enmod: apache2 enable mode rewrite ○ sudo service apache2 restart # restart the server

Page 13: Zend

Test Your Project

Navigate your web browser to:

localhost/project_name/public

Note:

This is not a professional way of hosting your project. The recommended is to create a VIRTUAL HOST

Page 14: Zend

http://localhost/project_name/public

Page 15: Zend

Creating A Virtual Host

● sudo gedit /etc/apache2/sites-available/project_name.conf

● Add these: <VirtualHost *:80>ServerName os.iti.gov.egDocumentRoot /var/www/html/project_name/publicSetEnv APPLICATION_ENV "development"<Directory /var/www/project_name>DirectoryIndex index.phpAllowOverride All</Directory></VirtualHost>

Page 16: Zend

Creating A Virtual Host

● Add your virtual host to hosts:sudo gedit /etc/hosts

And add this line:127.0.0.1 os.iti.gov.eg

● Enable the site on apache serversudo a2ensite project_name.conf

● Reload the serversudo service apache2 reload

Page 17: Zend

http://os.iti.gov.eg

Page 18: Zend

Create Zend Project

4. Adapt the database

● Create Database on MySQL ● Add it to the Zend Project using this command

zf configure db-adapter "adapter=PDO_MYSQL&dbname=mydb&host=localhost&username=root&password=admin" -s development

zf configure db-adapter

"adapter=PDO_MYSQL&dbname=mydb&host=localhost&username=root&passwo

rd=admin" -s development

Page 19: Zend
Page 20: Zend

Create Zend Model

Zf create model model_name

This create a model class under application/models

class Application_Model_User extends Zend_Db_Table_Abstract{

// Table name of the model classprotected $_name = 'users';

}

Note: To tell zend that model will link a table and not just a logic container class we put extends Zend_Db_Table_Abstract

Page 21: Zend

Create Zend Controller

Zf create controller controller_name

This creates a class controller under application/controllers

class UserController extends Zend_Controller_Action{

public function indexAction( ){

// action body}

}

Page 22: Zend

Create Zend Action

Zf create action action_name controller_name

This creates an action inside the controller class and a view file under application/view/script/controller_name/action_name.phtml

Page 23: Zend

Create Zend Layout

Zf enable layout

This creates layout master view page under application/layouts/script/layout.phtml

Contains:

<!-- header -->

<?php echo $this->layout()->content; ?>

<!-- footer -->

Page 24: Zend

User's System Example

In your MySQL Database create table:

CREATE TABLE users(id INT NOT NULL,fname CHAR(20),lname CHAR(20),email CHAR(50),gender CHAR(15),track CHAR(50),PRIMARY KEY(id)

);

Page 25: Zend

In model/User

function listUsers(){

return $this->fetchAll()->toArray();}

function deleteUser($id){

$this->delete("id=$id");}

function userDetails($id){

return $this->find($id)->toArray();}

Page 26: Zend

In controllers/UserController

public function listAction(){

$user_model = new Application_Model_User();$this->view->users = $user_model->listUsers();

}

public function detailsAction(){

$user_model = new Application_Model_User();$us_id = $this->_request->getParam("uid");$user = $user_model->userDetails($us_id);$this->view->user = $user[0];

}

Page 27: Zend

In controllers/UserController

public function deleteAction(){

// action body$user_model = new Application_Model_User();$us_id = $this->_request->getParam("uid");$user_model->deleteUser($us_id);$this->redirect("/user/list");

}

Page 28: Zend

In application/views/scripts/User/list

<table><?phpforeach($this->users as $key => $value){echo "<tr>"."<td>" . $value['id'] . "</td>" ."<td>" . $value['fname'] . "</td>" ."<td>" . $value['lname'] . "</td>" ."<td> <a href='details/uid/".$value['id']."'> Details </a> </td>" ."<td> <a href='delete/uid/".$value['id']."'> Delete </a> </td>" ."</tr>";}?></table>

Page 29: Zend

In application/layouts/script/layout<head><!-- Latest compiled and minified CSS --><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<!-- Optional theme --><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script></head>

Page 30: Zend

Lab Time

Page 31: Zend
Page 32: Zend
Page 33: Zend

Thank You That's all for day 1

Page 34: Zend

Zend Framework

Day 2

Page 35: Zend

Agenda

● Zend Form● Zend Form Validation ● Form Population ● Continue CRUD Operations● Lab Time

Page 36: Zend

Zend Form

● Zend framework offers a set of libraries to deal with forms creation, manipulation, validation.

● To create form simply use Zend Tool like this:

zf create form from_name

Page 37: Zend

Zend Form

● This Should create a class under Application/forms

class Application_Form_Add extends Zend_Form{

public function init(){

/* Form Elements & Other Definitions Here ... */}

}

Page 38: Zend

Zend Form

● First We set the submission method $this->setMethod(‘POST’);

● Then we define the form elements$id = new Zend_Form_Element_Hidden('id');

● For all elements we set and add different properties ● At the end we add the created elements to the form● And now we can create and use objects from out form in our views.

Page 39: Zend

Zend Form Validation and Filters

● We can add validators on form element for example the stringLength validator that takes the minimum and the maximum length of a string to accept.

● We can set Filters as well on elements for example StringTrip filter that remove the pre and post white spaces in a given string.

Page 40: Zend

Zend Element Form Example

$fname = new Zend_Form_Element_Text('fname');$fname->setLabel('First Name: ');$fname->setAttribs(Array('placeholder'=>'Example: Mohamed','class'=>'form-control'));$fname->setRequired();$fname->addValidator('StringLength', false, Array(4,20));$fname->addFilter('StringTrim');

Page 41: Zend

Zend Form Elements Example

$gender = new Zend_Form_Element_Select('gender');

$gender->setRequired();

$gender->addMultiOption('male','Male')->

addMultiOption('female','Female')->

addMultiOption('non','Prefer not to mention');

$gender->setAttrib('class', 'form-control');

Page 42: Zend

Zend Form Elements Example

$track_obj = new Application_Model_Track();

$allTracks = $track_obj->listAll();

$track = new Zend_Form_element_Select('track');

foreach($allTracks as $key=>$value)

{

$track->addMultiOption($value['id'], $value['name']);

}

Page 43: Zend

User Example Continue : Create

In model class

function addNewUser($userData){

$row = $this->createRow();$row->fname = $userData['fname'];$row->lname = $userData['lname'];$row->gender = $userData['gender'];$row->mail = $userData['mail'];$row->track = $userData['track'];$row->save();

}

Page 44: Zend

User Example Continue : Create In controller

public function addAction(){$form = new Application_Form_Add();$request = $this->getRequest();if($request->isPost()){

if($form->isValid($request->getPost())){$user_model = new Application_Model_User();$user_model-> addNewUser($request->getParams());$this->redirect('/user/list');

}}$this->view->user_form = $form; }

Page 45: Zend

User Example Continue : Update

In model

function updateUser($id, $userData){

$user_data['fname'] = $userData['fname'];$user_data['lname'] = $userData['lname'];$user_data['gender'] = $userData['gender'];$user_data['mail'] = $userData['mail'];$user_data['track'] = $userData['track'];$this->update($user_data, "id = $id");

}

Page 46: Zend

User Example Continue : Update In controller

public function editAction(){$form = new Application_Form_Add ();$user_model = new Application_Model_User ();$id = $this->_request->getParam('uid');$user_data = $user_model-> userDetails($id)[0];$form->populate($user_data);$this->view->user_form = $form;$request = $this->getRequest();if($request->isPost()){

if($form->isValid($request->getPost())){$user_model-> updateUser($id, $_POST);$this->redirect('/user/list');

}}

}

Page 47: Zend

User Example Continuepublic function listAction(){

$user_model = new Application_Model_User();$this->view->users = $user_model->listUsers();$track_form = new Application_Form_Track();$this->view->track_form = $track_form;$track_model = new Application_Model_Track();$request = $this->getRequest();if($request->isPost()){

if($track_form->isValid($request->getPost())){$track_model-> addTrack($request->getParams());$this->redirect('/user/new');

}}

Page 48: Zend

Lab Time

Page 49: Zend
Page 50: Zend
Page 51: Zend
Page 52: Zend

Thank You That's all for day 2

Page 53: Zend

Zend Framework

Day 3

Page 54: Zend

Agenda

● Session● Authentication● Intro to Social media API (log in using Facebook)● Lab Time

Page 55: Zend

Session

To start session, put a method in your Bootstrap.php to do that:

protected function _initSession(){

Zend_Session::start();$session = new Zend_Session_Namespace('Zend_Auth');$session->setExpirationSeconds(1800);

}

Page 56: Zend

Authentication

The process of authentication done in loginAction in user controller

public function loginAction(){//get login form and check for validation$login_form = new Application_Form_Login();if($this->_request->isPost()){

if($login_form->isValid($this->_request->getPost())){

// Code continue next slide ...

Page 57: Zend

//after check for validation get email and password to start auth

$email = $this->_request->getParam('email');$password = $this->_request->getParam('password');// get the default db adapter

$db = Zend_Db_Table::getDefaultAdapter();//create the auth adapter$authAdapter = new Zend_Auth_Adapter_DbTable ($db,'user', "email", 'password');

//set the email and password

$authAdapter->setIdentity($email);$authAdapter->setCredential(md5($password));

// Code Continue Next Slide ...

Page 58: Zend

//authenticate

$result = $authAdapter->authenticate();if($result->isValid()){//if the user is valid register his info in session

$auth = Zend_Auth::getInstance();//if the user is valid register his info in session

$auth = Zend_Auth::getInstance();$storage = $auth->getStorage();// write in session email & id & first_name$storage->write($authAdapter->getResultRowObject(array('email', 'id', 'first_name')));

// redirect to root index/index

return $this->redirect();}

Page 59: Zend

else{// if user is not valid send error message to view

$this->view->error_message = "Invalid Emai or Password!";

}

}

}

// that’s all for loginAction /* What we need next is to check if the user is logged in or * not so that we decide to display pages or not. This check * is performed in the constructor init() of the controllers */

Page 60: Zend

So Check for authentication before any request //On every init() of controller you have to check is authenticated or not

public function init( ) {$authorization = Zend_Auth::getInstance();if (!$authorization->hasIdentity() &&

$this->_request->getActionName() != 'login' &&$this->_request->getActionName() != 'register'){

$this->redirect("User/login");}

}

Page 61: Zend

Get username for login user in all pages

// In layout.php<nav class="navbar navbar-default navbar-fixed-top">

<p class="navbar-text" style="float:right;"><?php

$auth = Zend_Auth::getInstance();$storage = $auth-> getStorage();$sessionRead = $storage-> read();if (!empty($sessionRead)) {

$name = $sessionRead-> first_name;echo "Welcome " . $name;

?> <a class="btn btn-default navbar-btn" href="<?php echo$this->baseUrl() ?>/User/logout"> Logout </a><?php } ?> </p>

</nav>

Page 62: Zend

Login with facebook

Steps :

● Create facebook app which represent your site

https://developers.facebook.com/apps/

● Download Facebook library for php

https://developers.facebook.com/docs/php/gettingstarted

● Extract .zip folder and take Facebook folder in facebook-sdk-v5/src/Facebook and copy it in your-project/library

Page 63: Zend

● Include autoload.php in your_project/ public/index.php

// Ensure library/ is on include_path After include path of library

set_include_path(implode(PATH_SEPARATOR, array(

realpath(APPLICATION_PATH . '/../library'),

get_include_path(),

)));

/** Facebook JDK */

require_once 'Facebook/autoload.php'; Here

Page 64: Zend

● Create facebook button in loginAction and pass it to login.phtml

$fb = new Facebook\Facebook(['app_id' => '{app-id}', // Replace {app-id} with your app id'app_secret' => '{app-secret}','default_graph_version' => 'v2.2',]);$helper = $fb->getRedirectLoginHelper();$loginUrl = $helper->getLoginUrl($this->view->serverUrl() . $this->view->baseUrl() . 'User/fpAuth');$this->view->facebook_url = $loginUrl;

Page 65: Zend

● In login.phtml

<?php echo '<a href="' . htmlspecialchars( $this->facebook_url) . '"> Log in with Facebook!</a>'; ?>

● Now create your callback action fpauthAction

public function fpauthAction() {

// define instance from facebook

$fb = new Facebook\Facebook ([

'app_id' => '{app-id}’, // Replace {app-id} with your app id

'app_secret' => '{app-secret}’,

'default_graph_version ' => 'v2.2',

]);

Page 66: Zend

// use helper method of facebook for login

$helper = $fb->getRedirectLoginHelper();try {

$accessToken = $helper->getAccessToken();} catch (Facebook\Exceptions\FacebookResponseException $e) {

// When Graph returns an error (headers link)echo 'Graph returned an error: ' . $e->getMessage();Exit;

} catch (Facebook\Exceptions\FacebookSDKException $e) {// When validation fails or other local issuesecho 'Facebook SDK returned an error: ' . $e->getMessage();Exit;}

Page 67: Zend

// handle access toaken & print full error messageif (!isset($accessToken)) {

if ($helper->getError()) {header('HTTP/1.0 401 Unauthorized');echo "Error: " . $helper->getError() . "\n";echo "Error Code: " . $helper->getErrorCode() . "\n";echo "Error Reason: " . $helper->getErrorReason() . "\n";echo "Error Description: " . $helper->getErrorDescription() .

"\n";} else {

header('HTTP/1.0 400 Bad Request');echo 'Bad request';

}Exit;

}

Page 68: Zend

// Logged in// The OAuth 2.0 client handler helps us manage access tokens$oAuth2Client = $fb-> getOAuth2Client();//check if access token expiredif (!$accessToken->isLongLived()) {

// Exchanges a short-lived access token for a long-lived onetry {// try to get another access token

$accessToken = $oAuth2Client-> getLongLivedAccessToken ($accessToken);} catch (Facebook\Exceptions\FacebookSDKException $e) {

echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";

Exit;}

}

Page 69: Zend

//Sets the default fallback access token so we don't have to pass it to each request$fb->setDefaultAccessToken($accessToken);try {

$response = $fb->get('/me');$userNode = $response->getGraphUser();

} catch (Facebook\Exceptions\FacebookResponseException $e) {

// When Graph returns an errorecho 'Graph returned an error: ' . $e->getMessage();Exit;

} catch (Facebook\Exceptions\FacebookSDKException $e) {

// When validation fails or other local issuesecho 'Facebook SDK returned an error: ' . $e->getMessage();Exit;

}$fpsession = new Zend_Session_Namespace('facebook');// write in session email & id & first_name$fpsession->first_name = $userNode->getName();$this->redirect();}

Page 70: Zend

● In layout.php add another check for facebook session

$fbsession = new Zend_Session_Namespace('facebook');

elseif (isset($fbsession->first_name) && !empty (isset($fbsession->first_name))) {$name = $fbsession->first_name;echo "Welcome " . $name;?><a class="btn btn-default navbar-btn" href="<?php echo $this->baseUrl() ?>/User/fblogout"> Logout </a>

<?php

}

?>

Page 71: Zend

● Logout for facebook user

public function fblogoutAction() {

Zend_Session::namespaceUnset('facebook');

$this->redirect("/user/login");

}

Page 72: Zend

● Update init function in each controller to check for auth session and facebook session

public function init() {$authorization = Zend_Auth::getInstance();$fbsession = new Zend_Session_Namespace('facebook');if (!$authorization->hasIdentity() &&!isset($fbsession->first_name)) {

if ($this->_request->getActionName() != 'login' && $this->_request->getActionName() != 'register' && $this->_request->getActionName() != 'fpauth') { $this->redirect("User/login");

}}

}

Page 73: Zend

Notes

● Full Documentation for facebook library

https://developers.facebook.com/docs/php/gettingstarted

● When create facebook app check for this settings

Page 74: Zend
Page 75: Zend
Page 76: Zend

Lab Time

Page 77: Zend
Page 78: Zend
Page 79: Zend

Thank You That's all for day 3

Page 80: Zend

Zend Project

Project Specifications Lonely Planet Simulation: https://www.lonelyplanet.com/

Page 81: Zend

All System Features● Home Landing Page● Country Page● City Page● Car Lending● Hotel reservation● User Profile● Admin User● Login user ● SignUp

Page 82: Zend

Home Page

● Slider of the Top six high rated countries ● Under the slider box of the top six high rated cities within allover the countries ● In the menu destinations element is a drop down list with all countries

Page 83: Zend
Page 84: Zend

Country Page● When you Click on a country from the menus or the slider on homepage, You

will be transferred to country page.● In country page you will find all the country cities listed to user and he can

select any city to navigate to .

Page 85: Zend
Page 86: Zend

City Page● You will find the booking element in menu available now you can book car or

reserve hotel of the city available locations for cars and hotels of the city.● You will find the city description.● You will find the city location on the map. (BONUS)!● You will find user’s experience in this city with other user’ comments on

experiences.

Page 87: Zend
Page 88: Zend
Page 89: Zend
Page 90: Zend

BONUS !!

Page 91: Zend
Page 92: Zend

Car Rental Page● Car Rental Form is only available in city it is used to create car rental request● The form contains location for picking up , this location is filtered depending on

the city and pick time and leaving time.

Page 93: Zend
Page 94: Zend

Hotel Reservation Page● Hotel Form is only available in city , it is used to create hotel reservation ● Form contains:

○ List of available hotels in this city ○ From - to ○ Number of room members from 1 adult up to 4 adults in the room.

Page 95: Zend
Page 96: Zend

User Profile Page● Logged in user can view a profile page with a three lists (tables) shows:

○ User car rental requests ○ User hotel reservation requests

● Edit my data:○ User can edit some of his data for example user name ○ HINT: Use the id from user session to fetch all user data from the database.

Page 97: Zend

Admin Page● The Admin User only is who authorized to CRUD the:

○ Countries○ Cities○ Locations ○ Hotels

While the normal user can only crud experience and comments

● Admin user Can block normal user from being logged in so that he will not be able to: (BONUS)!

○ Book cars or reserve hotel○ Post experience or comment on experience ○ Can navigate all the pages except profile page

Page 98: Zend

User Login ● Login either with system authentication or Facebook authentication.● Login with Twitter and Google + (BONUS)!.● User can share experience on facebook and twitter (BONUS)!.● User can post an experience on a city.● User can Comment on experiences. ● User can rent a car, reserve a hotel. ● User Can Update his data.

● Sign up using system only no API needed.

Page 99: Zend

Project delivery ● The Due Date Thursday 7 April, 2016 12:00am.

● Team Leader should send the Git Repository URL within this due date.● Project Presentation on Saturday 9 April, 2016 12:00pm.

Page 100: Zend

Thanks Good Luck

Mohamed Ramadan