SlideShare a Scribd company logo
Zend Framework
Day 1
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
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.
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.
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
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.
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
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
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 ”
Create Zend Project
Four Steps:
1. Create project
zf create project /var/www/html/project_name
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
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.php
AllowOverride All
</Directory>
○ sudo a2enmod rewrite #a2enmod: apache2 enable mode rewrite
○ sudo service apache2 restart # restart the server
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
http://localhost/project_name/public
Creating A Virtual Host
● sudo gedit /etc/apache2/sites-available/project_name.conf
● Add these:
<VirtualHost *:80>
ServerName os.iti.gov.eg
DocumentRoot /var/www/html/project_name/public
SetEnv APPLICATION_ENV "development"
<Directory /var/www/project_name>
DirectoryIndex index.php
AllowOverride All
</Directory>
</VirtualHost>
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 server
sudo a2ensite project_name.conf
● Reload the server
sudo service apache2 reload
http://os.iti.gov.eg
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
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 class
protected $_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
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
}
}
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
Create Zend Layout
Zf enable layout
This creates layout master view page under application/layouts/script/layout.phtml
Contains:

<?php echo $this->layout()->content; ?>
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)
);
In model/User
function listUsers()
{
return $this->fetchAll()->toArray();
}
function deleteUser($id)
{
$this->delete("id=$id");
}
function userDetails($id)
{
return $this->find($id)->toArray();
}
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];
}
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");
}
In application/views/scripts/User/list
<table>
<?php
foreach($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>
In application/layouts/script/layout
<head>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.
min.css" integrity="sha384-
1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

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

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous"></script>
</head>
Lab Time
Zend
Zend
Thank You
That's all for day 1
Zend Framework
Day 2
Agenda
● Zend Form
● Zend Form Validation
● Form Population
● Continue CRUD Operations
● Lab Time
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
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 ... */
}
}
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.
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.
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');
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');
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']);
}
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();
}
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; }
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");
}
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');
}
}
}
User Example Continue
public 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');
}
}
Lab Time
Zend
Zend
Zend
Thank You
That's all for day 2
Zend Framework
Day 3
Agenda
● Session
● Authentication
● Intro to Social media API (log in using Facebook)
● Lab Time
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);
}
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 ...
//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 ...
//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();
}
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
*/
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");
}
}
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>
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
● 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
● Create facebook button in loginAction and pass it to login.phtml
$fb = new FacebookFacebook([
'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;
● 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 FacebookFacebook ([
'app_id' => '{app-id}’, // Replace {app-id} with your app id
'app_secret' => '{app-secret}’,
'default_graph_version ' => 'v2.2',
]);
// use helper method of facebook for login
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
}
catch (FacebookExceptionsFacebookResponseException $e) {
// When Graph returns an error (headers link)
echo 'Graph returned an error: ' . $e->getMessage();
Exit;
}
catch (FacebookExceptionsFacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
Exit;
}
// handle access toaken & print full error message
if (!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;
}
// Logged in
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb-> getOAuth2Client ();
//check if access token expired
if (!$accessToken-> isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
// try to get another access token
$accessToken = $oAuth2Client-> getLongLivedAccessToken ($accessToken);
}
catch (FacebookExceptionsFacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $helper-
>getMessage() . "</p>nn";
Exit;
}
}
//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 (FacebookExceptionsFacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
Exit;
}
catch (FacebookExceptionsFacebookSDKException $e) {
// When validation fails or other local issues
echo '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();
}
● 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
}
?>
● Logout for facebook user
public function fblogoutAction() {
Zend_Session::namespaceUnset('facebook');
$this->redirect("/user/login");
}
● 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");
}
}
}
Notes
● Full Documentation for facebook library
https://developers.facebook.com/docs/php/gettingstarted
● When create facebook app check for this settings
Zend
Zend
Lab Time
Zend
Zend
Thank You
That's all for day 3
Zend Project
Project Specifications
Lonely Planet Simulation: https://www.lonelyplanet.com/
All System Features
● Home Landing Page
● Country Page
● City Page
● Car Lending
● Hotel reservation
● User Profile
● Admin User
● Login user
● SignUp
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
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 .
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.
Zend
Zend
Zend
BONUS !!
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.
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.
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.
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
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.
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.
ThanksGood Luck
Mohamed Ramadan

More Related Content

Zend

  • 2. 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
  • 3. 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.
  • 4. 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.
  • 5. 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
  • 6. 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.
  • 7. 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
  • 8. 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
  • 9. 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 ”
  • 10. Create Zend Project Four Steps: 1. Create project zf create project /var/www/html/project_name
  • 11. 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
  • 12. 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.php AllowOverride All </Directory> ○ sudo a2enmod rewrite #a2enmod: apache2 enable mode rewrite ○ sudo service apache2 restart # restart the server
  • 13. 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
  • 15. Creating A Virtual Host ● sudo gedit /etc/apache2/sites-available/project_name.conf ● Add these: <VirtualHost *:80> ServerName os.iti.gov.eg DocumentRoot /var/www/html/project_name/public SetEnv APPLICATION_ENV "development" <Directory /var/www/project_name> DirectoryIndex index.php AllowOverride All </Directory> </VirtualHost>
  • 16. 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 server sudo a2ensite project_name.conf ● Reload the server sudo service apache2 reload
  • 18. 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
  • 20. 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 class protected $_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
  • 21. 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 } }
  • 22. 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
  • 23. 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 -->
  • 24. 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) );
  • 25. In model/User function listUsers() { return $this->fetchAll()->toArray(); } function deleteUser($id) { $this->delete("id=$id"); } function userDetails($id) { return $this->find($id)->toArray(); }
  • 26. 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]; }
  • 27. 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"); }
  • 28. In application/views/scripts/User/list <table> <?php foreach($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>
  • 29. 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>
  • 33. Thank You That's all for day 1
  • 35. Agenda ● Zend Form ● Zend Form Validation ● Form Population ● Continue CRUD Operations ● Lab Time
  • 36. 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
  • 37. 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 ... */ } }
  • 38. 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.
  • 39. 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.
  • 40. 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');
  • 41. 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');
  • 42. 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']); }
  • 43. 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(); }
  • 44. 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; }
  • 45. 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"); }
  • 46. 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'); } } }
  • 47. User Example Continue public 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'); } }
  • 52. Thank You That's all for day 2
  • 54. Agenda ● Session ● Authentication ● Intro to Social media API (log in using Facebook) ● Lab Time
  • 55. 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); }
  • 56. 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 ...
  • 57. //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 ...
  • 58. //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(); }
  • 59. 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 */
  • 60. 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"); } }
  • 61. 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>
  • 62. 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
  • 63. ● 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
  • 64. ● Create facebook button in loginAction and pass it to login.phtml $fb = new FacebookFacebook([ '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;
  • 65. ● 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 FacebookFacebook ([ 'app_id' => '{app-id}’, // Replace {app-id} with your app id 'app_secret' => '{app-secret}’, 'default_graph_version ' => 'v2.2', ]);
  • 66. // use helper method of facebook for login $helper = $fb->getRedirectLoginHelper(); try { $accessToken = $helper->getAccessToken(); } catch (FacebookExceptionsFacebookResponseException $e) { // When Graph returns an error (headers link) echo 'Graph returned an error: ' . $e->getMessage(); Exit; } catch (FacebookExceptionsFacebookSDKException $e) { // When validation fails or other local issues echo 'Facebook SDK returned an error: ' . $e->getMessage(); Exit; }
  • 67. // handle access toaken & print full error message if (!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; }
  • 68. // Logged in // The OAuth 2.0 client handler helps us manage access tokens $oAuth2Client = $fb-> getOAuth2Client (); //check if access token expired if (!$accessToken-> isLongLived()) { // Exchanges a short-lived access token for a long-lived one try { // try to get another access token $accessToken = $oAuth2Client-> getLongLivedAccessToken ($accessToken); } catch (FacebookExceptionsFacebookSDKException $e) { echo "<p>Error getting long-lived access token: " . $helper- >getMessage() . "</p>nn"; Exit; } }
  • 69. //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 (FacebookExceptionsFacebookResponseException $e) { // When Graph returns an error echo 'Graph returned an error: ' . $e->getMessage(); Exit; } catch (FacebookExceptionsFacebookSDKException $e) { // When validation fails or other local issues echo '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(); }
  • 70. ● 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 } ?>
  • 71. ● Logout for facebook user public function fblogoutAction() { Zend_Session::namespaceUnset('facebook'); $this->redirect("/user/login"); }
  • 72. ● 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"); } } }
  • 73. Notes ● Full Documentation for facebook library https://developers.facebook.com/docs/php/gettingstarted ● When create facebook app check for this settings
  • 79. Thank You That's all for day 3
  • 80. Zend Project Project Specifications Lonely Planet Simulation: https://www.lonelyplanet.com/
  • 81. All System Features ● Home Landing Page ● Country Page ● City Page ● Car Lending ● Hotel reservation ● User Profile ● Admin User ● Login user ● SignUp
  • 82. 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
  • 84. 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 .
  • 86. 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.
  • 92. 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.
  • 94. 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.
  • 96. 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.
  • 97. 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
  • 98. 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.
  • 99. 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.