Zend Framework
-
Upload
perttu-myry -
Category
Documents
-
view
2.252 -
download
1
description
Transcript of Zend Framework
10.04.2023Perttu Myry
Zend FrameworkCommon PHP Application Issues, Design Patterns and Zend Framework
Perttu Myry 10.04.2023
Zend FrameworkCommon issues in PHP applications
Common issues in PHP applications Useful design patterns and practices Introduction to Zend Framework Zend Framework basics Building a demo application Resources
Perttu Myry 10.04.2023
Zend FrameworkCommon issues in PHP applications
Before we head into Zend Framework (or just ZF) let’s list some common PHP application architecture issues
By definition PHP is a scripting language, it’s easy to do it ”wrong”
PHP can be embedded into HTML code Suddenly you are doing database queries right
next to your HTML code – a task you should be definitely doing in some other layer of your application architecture
Everything gets tangled up
Perttu Myry 10.04.2023
Zend FrameworkCommon issues in PHP applications
Debugging becomes hard work Maintenance and development of your
application is a nightmare when code is not separated properly
Quite often there no single entry point to your application which makes it hard to manage such operations which should be done for each request
Requires and includes can become hard to manage
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
Common issues in PHP applications Useful design patterns and practices Introduction to Zend Framework Zend Framework basics Building a demo application Resources
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
Use a version control system such as SVN or Git Even in single developer projects it’s useful
(code diff, history, branches, development and production versions are easy to separate)
In multiple developer environments it’s somewhat a necessity (see who has done what, merge changes, resolve conflicts)
It’s good to know how to use highly popular Git (for example, if you would like to contribute to a project in GitHub)
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
MVC (model-view-controller) pattern Most importantly separates code into
logical structures Model consists of application data and
business rules Controller mediates input, converting it to
commands for the model or view View can be any output representation of
data
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
This way you are not doing database queries embedded in your HTML code (view)
Instead you have layer in your application for these kind of operations (model)
There is a layer between view and model (controller) which takes care of handling user input to model and also handling model data properly to view
Everything is properly separated, not all tangled up in single spaghetti code
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
There are tons of design patterns out there In addition to MVC I will introduce factory
and singleton using some examples Factory pattern can hide complex object
instantiation logic inside it Can avoid duplicate code One common indicator when factory
pattern should be used can be a long if-elseif-else or switch-case list
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices// Somewhat ugly way to instantiate a new carif($type === 'ford') { return new Ford();} else if($type === 'chevrolet') { return new Chevrolet();} else if($type === 'volvo') { return new Volvo();} else { throw new Exception('unknown car type ' . $type);}
// Using switch-case doesn't make it any betterswitch($type) { case 'ford': return new Ford(); break; case 'chevrolet': return new Chevrolet(); break; case 'volvo': return new Volvo(); break; default: throw new Exception('unknown car type ' . $type);}
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
// That was yet rather simple, what if car instantiation is more complex and you would have to do certain steps for every car you create
// Car is a general class which is used in many places in our application, but in this specific piece of our application we want to make all cars have certain properties$car = new Ford();$car->setLocation('USA');$car->setColor('red');
// Still that is rather simple, but already now we can do a lot better, let's take a look how this would look like using factory$factory = new RedCarsFactoryUSA();$car = $factory->createCar($type);
// Once properly implemented, that’s all that it really takes, just two lines instead of massive if-elses, let's dive bit more into details in next couple slides
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
// Simple CarFactory interfaceinterface CarFactory { public function createCar($type);}
// CarFactory class implementing CarFactory interfaceclass CarFactory implements CarFactory {
public function createCar($type) { // Require proper file and do it just once require_once 'path/to/cars/' . $type . '.php';
// Capitalized first character will be the class name $class = ucfirst($type);
// Create and return new car return new $class; }
}
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
// This factory extends CarFactory which implements CarFactory interfaceclass RedCarsFactoryUSA extends CarFactory {
public function createCar($type) { // Create new car $car = parent::createCar($type);
// Set such car properties we want to have in this factory $car->setLocation('USA'); $car->setColor('red');
// Return car return $car; }
}
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
// Let's also create a simple abstract Car classabstract class Car {
protected $location = null; protected $color = null;
public function setLocation($location) { $this->location = $location; }
public function setColor($color) { $this->color = $color; }
public function log() { echo 'Car ' . ucfirst(get_class($this)) . ' is ' . $this->color . ' and it is located in ' . $this->location . '<br />'; }
}
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
// And some examples how to use this setup
// This code would go into path/to/cars/ford.phpclass Ford extends Car { /* Ford specific code could be put here */ }
// This code would go into path/to/cars/volvo.phpclass Volvo extends Car { /* Volvo specific code could be put here */ }
// Create new default factory$defaultFactory = new CarFactory ();
// How to create cars using default factory$car = $defaultFactory->createCar('ford');$car->log(); // "Car Ford is NULL and it is located in NULL"$car->setColor('blue');$car->setLocation('Germany');$car->log(); // "Car Ford is blue and it is located in Germany"
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
// And some red car USA factory examples
$redCarsFactoryUSA = new RedCarsFactoryUSA();
$car = $redCarsFactoryUSA->createCar('ford');$car->log(); // "Car Ford is red and it is located in USA"
$car = $redCarsFactoryUSA->createCar('volvo');$car->log(); // "Car Volvo is red and it is located in USA“
// Ford is shipped to China...$car->setLocation('China');$car->log(); // "Car Volvo is red and it is located in China"
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
In singleton pattern only one instance of class can be initiated
Quite common implementation to get access to this instance is getInstance() method
List of singleton common uses from Wikipedia The Abstract Factory, Builder, and Prototype
patterns can use Singletons in their implementation
Facade Objects are often Singletons because only one Facade object is required
State objects are often Singletons
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices
Classic way to utilize singleton could be, for example, Config class
When request is initialized, you can initialize certain settings in your Config, such as database host
Later on in your script execution you want to open up database connection so you need to know what database host you should connect to
It’s argued that better way to solve these kind of design issues would be to use dependency injection pattern, but I shall not dive into that topic in this presentation
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practices// --- Without singleton your code might look something like this
// Let's say you have this in init.php file$config = new Config();$config->set('db_host', '127.0.0.1');
// And this in database.php file$config = new Config();// This wouldn't return '127.0.0.1' (that was set in another instance)$config->get('db_host');
// --- With singleton your PHP code could look something like this
// When you set this in init.php
Config::getInstance()->set('db_host', '127.0.0.1');
// You will always get the value from same instance
Config::getInstance()->get('db_host');
Perttu Myry 10.04.2023
Zend FrameworkUseful design patterns and practicesclass Config { private static $instance = null; // private static variable for instance private $settings = array(); // private variable for settings
private function __construct() {} // private constructor
public static function getInstance() { if(self::$instance === null) { // initiate only once self::$instance = new Config(); } return self::$instance; }
public function set($name, $value) { $this->settings[$name] = $value; }
public function get($name) { if(array_key_exists($name, $this->settings)) { return $this->settings[$name]; } return null; }}
Perttu Myry 10.04.2023
Zend FrameworkIntroduction to Zend Framework
Common issues in PHP applications Useful design patterns and practices Introduction to Zend Framework Zend Framework basics Building a demo application Resources
Perttu Myry 10.04.2023
Zend FrameworkIntroduction to Zend Framework
Zend, Zend Engine, Zend Framework? Zend Technologies Ltd, commonly known
as Zend, is a company Its founders, Andi Gutmans and Zeev
Suraski, are key contributors to PHP and the creators of the core PHP scripting engine, the Zend Engine
Zend Framework, or simply ZF, is an open source framework
Perttu Myry 10.04.2023
Zend FrameworkIntroduction to Zend Framework
”The most popular framework for modern, high-performing PHP applications”http://framework.zend.com/
“Zend Framework 2 is an open source framework for developing web applications and services using PHP 5.3+. Zend Framework 2 uses 100% object-oriented code and utilises most of the new features of PHP 5.3, namely namespaces, late static binding, lambda functions and closures.
Zend Framework 2 evolved from Zend Framework 1, a successful PHP framework with over 15 million downloads.”http://framework.zend.com/about/
Perttu Myry 10.04.2023
Zend FrameworkIntroduction to Zend Framework
Why use Zend Framework? Modular: Building blocks that can be used piece by piece
with other applications or frameworks Secure: All the cryptographic and secure coding tools
you need to do things right Extensible: Easy to adapt the framework to your needs Community: A vibrant and active contributor and user
base for getting help and giving back High Performing: Engineered with performance tuning in
mind Enterprise Ready: A proven history of success running
business critical and high-usage applicationshttp://framework.zend.com/
Perttu Myry 10.04.2023
Zend FrameworkIntroduction to Zend Framework
And some personal opinions Works as a good base for web
applications Helps you towards good architecture
(MVC, directory structure, bootstrapping, autoloading, configs etc.)
Has lots of ready made components which means less work for you
Actively developed
Perttu Myry 10.04.2023
Zend FrameworkIntroduction to Zend Framework
In this presentation I’m going to focus on ZF 1 for couple reasons ZF 2 was released in September 2012,
just two months ago I have personal experience only from ZF 1 A lot has changed in ZF 2
If you are looking into choosing ZF as base for you web application, I suggest you take a look at ZF 2
Perttu Myry 10.04.2023
Zend FrameworkZend Framework application basics
Common issues in PHP applications Useful design patterns and practices Introduction to Zend Framework Zend Framework basics Building a demo application Resources
Perttu Myry 10.04.2023
Zend FrameworkZend Framework basics
First we are going to take a look at proposed directory structure for ZF project
At first glance that doesn’t look too bad, let’s get into details why all these folders and files are here
<project name>|-- application| |-- Bootstrap.php| |-- configs| | `-- application.ini| |-- controllers| | |-- ErrorController.php| | `-- IndexController.php| |-- models| `-- views| |-- helpers| `-- scripts| |-- error| | `-- error.phtml| `-- index| `-- index.phtml|-- library|-- public| |-- .htaccess| `-- index.php`-- tests |-- application | `-- bootstrap.php |-- library | `-- bootstrap.php `-- phpunit.xml
Perttu Myry 10.04.2023
Zend FrameworkZend Framework application basics
Bootstrapping Zend Framework’s controller uses the
Front Controller design pattern Routes all requests through a single
index.php file Ensures that the environment is set up
correctly for running the application
Perttu Myry 10.04.2023
Zend FrameworkZend Framework application basics
URL structure ZF uses forward slash (/) as URL separator After base URL your ZF application consists
of module, controller and action parameters If not defined ZF will use default value which
is “default” for modules and “index” for controllers and actions
After that URL consists of /param/value pairs (corresponds to ¶m=value URL structure)
Perttu Myry 10.04.2023
Zend FrameworkZend Framework application basics
Some URL examples Here base means the URL to your application (public
folder), such as http://localhost/zfdemo/ base: default module, controller and action (same as
base/default/index/index) base/foo/bar: in case foo is not a module, refers to
default module’s foo controller’s bar action base/foo/bar: in case foo is a module, refers to foo
module’s bar controller’s default action (if foo would be both controller and module name, you could refer to default module’s foo controller by base/default/foo/bar)
base/default/foo/bar/id/123/name/john: default module’s foo controller’s bar action gets two request parameters “id” which value is “123” and “name” which value is “john”
Perttu Myry 10.04.2023
Zend FrameworkZend Framework application basics
Autoloader PHP 5 introduced autoloading Zend Framework has its own autoloader
which is based on this autoloading This means you don’t have to write any
include or require statements (unless you are using a class or interface which is located outside your autoloading definitions)
Perttu Myry 10.04.2023
Zend FrameworkBuilding a demo application
Common issues in PHP applications Useful design patterns and practices Introduction to Zend Framework Zend Framework basics Building a demo application Resources
Perttu Myry 10.04.2023
Zend FrameworkBuilding a demo application
Let’s go through the Zend Framework 1 Getting started guide
Perttu Myry 10.04.2023
Zend FrameworkResources
Common issues in PHP applications Useful design patterns and practices Introduction to Zend Framework Zend Framework basics Building a demo application Resources
Perttu Myry 10.04.2023
ResourcesBooks
Zend Framework in Action Head First Design Patterns
Perttu Myry 10.04.2023
ResourcesLinks
Getting started with Zend Framework tutorial by Rob Allen
Apache mod_rewrite reference documentation