PHP 5
. Zend Framework is often called a 'component library', because it has many loosely coupled components that you can use more or less independently. But Zend Framework also provides an advanced Model-View-Controller (MVC) implementation that can be used to establish a basic structure for your Zend Framework applications. Zend_Controller
, Zend_Layout
, Zend_Config
, Zend_Db
, Zend_Db_Table
, Zend_Registry
, along with a few view helpers.[server]$ php composer.phar self-update
[server]$ php composer.phar install
Page | Description |
---|---|
Home | This will display the list of albums and provide links to edit and delete them. Also, a link to enable adding new albums will be provided. |
Add new album | This page will provide a form for adding a new album. |
Edit album | This page will provide a form for editing an album. |
Delete album | This page will confirm that we want to delete an album and then delete it. |
AlbumController
within our Album module as four actions. The four actions will be :Page | Controller | Action |
---|---|---|
Home | AlbumController |
index |
Add new album | AlbumController |
add |
Edit album | AlbumController |
edit |
Delete album | AlbumController |
delete |
namespace Album;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return [
'controllers' => [
'factories' => [
Controller\AlbumController::class => InvokableFactory::class,
],
],
// The following section is new and should be added to your file:
'router' => [
'routes' => [
'album' => [
'type' => Segment::class,
'options' => [
'route' => '/album[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\AlbumController::class,
'action' => 'index',
],
],
],
],
],
'view_manager' => [
'template_path_stack' => [
'album' => __DIR__ . '/../view',
],
],
];
/album[/:action[/:id]]
which will match any URL that starts with /album
. The next segment will be an optional action name, and then finally the next segment will be mapped to an optional id. The square brackets indicate that a segment is optional. The constraints section allows us to ensure that the characters within a segment are as expected, so we have limited actions to starting with a letter and then subsequent characters only being alphanumeric, underscore, or hyphen. We also limit the id to digits.URL | Page | Action |
---|---|---|
/album |
Home (list of albums) | index |
/album/add |
Add new album | add |
/album/edit/2 |
Edit album with an id of 2 | edit |
/album/delete/4 |
Delete album with an id of 4 | delete |
{Controller name}Controller;
note that {Controller name}
must start with a capital letter. This class lives in a file called {Controller name}Controller.php
within the Controller subdirectory for the module; in our case that is module/Album/src/Controller/
. Each action is a public method within the controller class that is named {action name}Action
, where {action name}
should start with a lower case letter.Zend\Stdlib\Dispatchable
interface. The framework provides two abstract classes that do this for us: Zend\Mvc\Controller\AbstractActionController
and Zend\Mvc\Controller\AbstractRestfulController.
We'll be using the standard AbstractActionController
, but if you’re intending to write a RESTful web service, AbstractRestfulController may be useful.zf-tutorials/module/Album/src/Controller/AlbumController.php
:namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AlbumController extends AbstractActionController
{
public function indexAction()
{
}
public function addAction()
{
}
public function editAction()
{
}
public function deleteAction()
{
}
}
URL | Method called |
---|---|
http://zf-tutorial.localhost/album |
Album\Controller\AlbumController::indexAction |
http://zf-tutorial.localhost/album/add |
Album\Controller\AlbumController::addAction |
http://zf-tutorial.localhost/album/edit |
Album\Controller\AlbumController::editAction |
http://zf-tutorial.localhost/album/delete |
Album\Controller\AlbumController::deleteAction |
bootstrapped/loaded/initialized
before the request is completed. $b = new B(new A());
namespace My {
class A
{
/* Some useful functionality */
}
class B
{
protected $a = null;
public function __construct(A $a)
{
$this->a = $a;
}
}
}
$b = new B(new A());
$di = new Zend\Di\Di;
$b = $di->get('My\B'); // will produce a B object that is consuming an A object
Di::newInstance()
method:$b = $di->newInstance('My\B');
namespace My {
class A
{
protected $username = null;
protected $password = null;
public function __construct($username, $password)
{
$this->username = $username;
$this->password = $password;
}
}
class B
{
protected $a = null;
public function __construct(A $a)
{
$this->a = $a;
}
}
class C
{
protected $b = null;
public function __construct(B $b)
{
$this->b = $b;
}
}
}
$di = new Zend\Di\Di;
$di->getInstanceManager()->setProperty('A', 'username', 'MyUsernameValue');
$di->getInstanceManager()->setProperty('A', 'password', 'MyHardToGuessPassword%$#');
$c = $di->get('My\C');
// or
$c = $di->newInstance('My\C');
$parameters = array(
'username' => 'MyUsernameValue',
'password' => 'MyHardToGuessPassword%$#',
);
$c = $di->get('My\C', $parameters);
// or
$c = $di->newInstance('My\C', $parameters);
namespace My {
class B
{
protected $a;
public function setA(A $a)
{
$this->a = $a;
}
}
}
$c = $di->get('C')
, will once again know how to fill the dependencies when needed to create an object of type C.Zend\Authentication
component provides an API for authentication and includes concrete authentication adapters for common use case scenarios.Zend\Authentication
.application/configs/application.ini
location. Zend_Auth
and Zend_Acl
, such as :Zend_Auth | Zend_Acl |
---|---|
Zend_Auth utilizes the method like OpenID, LDAP, and HTTP to provide the confirmation. | Zend_Acl utilizes Access Control List for approval. |
Zend_Auth gives the validation protocol to the clients utilizing numerous methods. | Zend_Acl is utilized for approval purposes. |
Zend_Auth confirms checking and providing the certifications to the client's system. | Zend_Acl utilizes the list of parts that are being implemented, just the approved individuals. |
Zend_Auth supports the authentication stages features. | Zend_Acl supports the propelled definitions with features of different legacy and other similar highlights. |
Zend_Auth gives an environment to the framework through which the user is authenticated for utilize. | Zend_Acl plays out a few tasks on the particular assets that need to be composed on the system. |
Zend_Search_Lucene
is a PHP usage that brings full binary similarity with Java Lucene.Zend\Authentication\Adapter\DbTable
provides the ability to authenticate against credentials stored in a database table. Because Zend\Authentication\Adapter\DbTable
requires an instance of Zend\Db\Adapter\Adapter
to be passed to its constructor, each instance is bound to a particular database connection. Other configuration options may be set through the constructor and through instance methods, one for each option.MD5(?)
‘ or ‘PASSWORD(?)‘
, a developer may apply such arbitrary SQL upon input credential data. Since these functions are specific to the underlying RDBMS, check the database manual for the availability of such functions for your database system.Zend\Authentication\Adapter\DbTable
constructor requires an instance of Zend\Db\Adapter\Adapter
that serves as the database connection to which the authentication adapter instance is bound. First, the database connection should be created.use Zend\Db\Adapter\Adapter as DbAdapter;
// Create a SQLite database connection
$dbAdapter = new DbAdapter(array(
'driver' => 'Pdo_Sqlite',
'database' => 'path/to/sqlite.db'
));
// Build a simple table creation query
$sqlCreate = 'CREATE TABLE [users] ('
. '[id] INTEGER NOT NULL PRIMARY KEY, '
. '[username] VARCHAR(50) UNIQUE NOT NULL, '
. '[password] VARCHAR(32) NULL, '
. '[real_name] VARCHAR(150) NULL)';
// Create the authentication credentials table
$dbAdapter->query($sqlCreate);
// Build a query to insert a row for which authentication may succeed
$sqlInsert = "INSERT INTO users (username, password, real_name) "
. "VALUES ('my_username', 'my_password', 'My Real Name')";
// Insert the data
$dbAdapter->query($sqlInsert);
Zend\Authentication\Adapter\Http
provides a mostly-compliant implementation of RFC-2617
, Basic and Digest HTTP Authentication. Digest authentication is a method of HTTP authentication that improves upon Basic authentication by providing a way to authenticate without having to transmit the password in clear text across the network.stale
” support, and increased replay attack protection.auth-int
”.Zend\Authentication\Validator\Authentication
provides the ability to utilize a validator for an InputFilter in the instance of a Form or for single use where you simply want a true/false value and being able to introspect the error.use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Validator\Authentication as AuthenticationValidator;
$service = new AuthenticationService();
$adapter = new My\Authentication\Adapter();
$validator = new AuthenticationValidator(array(
'service' => $service,
'adapter' => $adapter,
));
$validator->setCredential('myCredentialContext');
$validator->isValid('myIdentity', array(
'myCredentialContext' => 'myCredential',
));
setOptions()
method.use Zend\Barcode\Object;
$options = array('text' => 'ZEND-FRAMEWORK', 'barHeight' => 40);
// Case 1: constructor
$barcode = new Object\Code39($options);
// Case 2: setOptions()
$barcode = new Object\Code39();
$barcode->setOptions($options);
// Case 3: individual setters
$barcode = new Object\Code39();
$barcode->setText('ZEND-FRAMEWORK')
->setBarHeight(40);
setOptions()
method.use Zend\Barcode\Renderer;
$options = array('topOffset' => 10);
// Case 1
$renderer = new Renderer\Pdf($options);
// Case 2
$renderer = new Renderer\Pdf();
$renderer->setOptions($options);
// Case 3
$renderer = new Renderer\Pdf();
$renderer->setTopOffset(10);
use Zend\Cache\PatternFactory;
use Zend\Cache\Pattern\PatternOptions;
// Via the factory:
$callbackCache = PatternFactory::factory('callback', array(
'storage' => 'apc',
'cache_output' => true,
));
// OR, the equivalent manual instantiation:
$callbackCache = new \Zend\Cache\Pattern\CallbackCache();
$callbackCache->setOptions(new PatternOptions(array(
'storage' => 'apc',
'cache_output' => true,
)));
Option | Data Type | Default Value | Description |
---|---|---|---|
storage | string array Zend\Cache\Storage\StorageInterface | <none> | The storage to write/read cached data |
cache_output | boolean | true | Cache output of callback |
ObjectCache
pattern is an extension to the CallbackCache pattern. It has the same methods but instead it generates the internally used callback in base of the configured object and the given method name.use Zend\Cache\PatternFactory;
$object = new stdClass();
$objectCache = PatternFactory::factory('object', array(
'object' => $object,
'storage' => 'apc'
));
Configuration Options :
Option | Data Type | Default Value | Description |
---|---|---|---|
storage | string array Zend\Cache\Storage\StorageInterface | <none> | The storage to write/read cached data |
object | object | <none> | The object to cache methods calls of |
object_key | null string | <Class name of object> | A hopefully unique key of the object |
cache_output | boolean | true | Cache output of callback |
cache_by_default | boolean | true | Cache method calls by default |
object_cache_methods | array | [] | List of methods to cache (If cache_by_default is disabled) |
object_non_cache_methods | array | [] | List of methods to no-cache (If cache_by_default is enabled) |
object_cache_magic_properties | boolean | false | Cache calls of magic object properties |
Zend\Captcha\AdapterInterface
, which looks like the following :namespace Zend\Captcha;
use Zend\Validator\ValidatorInterface;
interface AdapterInterface extends ValidatorInterface
{
public function generate();
public function setName($name);
public function getName();
// Get helper name used for rendering this captcha type
public function getHelperName();
}
CAPTCHA
identifier. The most interesting methods are generate()
and render()
. generate()
is used to create the CAPTCHA
token. This process typically will store the token in the session so that you may compare against it in subsequent requests. render()
is used to render the information that represents the CAPTCHA, be it an image, a figlet, a logic problem, or some other CAPTCHA.$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
Zend_Controller_Request_Http
object which is then processed by Zend_Controller_Dispatcher_Standard
.Zend_Controller_Router_Rewrite
is the standard framework router.Zend\Console\Prompt
classes and their example usage.show()
method.use Zend\Console\Prompt;
$confirm = new Prompt\Confirm('Are you sure you want to continue?');
$result = $confirm->show();
if ($result) {
// the user chose to continue
}
prompt()
method :use Zend\Console\Prompt;
$result = Prompt\Confirm::prompt('Are you sure you want to continue?');
if ($result) {
// the user chose to continue
}
namespace Application;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Console\Adapter\AdapterInterface as Console;
use Zend\Console\Exception\RuntimeException;
class ConsoleController extends AbstractActionController
{
public function testAction()
{
$console = $this->getServiceLocator()->get('console');
if (!$console instanceof Console) {
throw new RuntimeException('Cannot obtain console adapter. Are we running in a console?');
}
}
}
Zend\Console
without MVC, we can get adapter using the following code :use Zend\Console\Console;
use Zend\Console\Exception\RuntimeException as ConsoleException;
try {
$console = Console::getInstance();
} catch (ConsoleException $e) {
// Could not get console adapter - most likely we are not running inside a console window.
}
Zend\Console\Getopt
class helps command-line applications to parse their options and arguments.-c
enables different features in grep
, ls
, and tar
.ls -1str
” uses a cluster of four short flags. This command is equivalent to “ls -1 -s -t -r
”. Only single-character flags can be clustered. You cannot make a cluster of long flags.--user=root
mydatabase, mysql is a command, --user=root
is an option, --user is a flag, root is a parameter to the option, and mydatabase is an argument but not an option by our definition.Zend\Console\Getopt
provides an interface to declare which flags are valid for your application, output an error and usage message if they use an invalid flag, and report to your application code which flags the user specified.Zend\Console\Getopt
class takes from one to three arguments. The first argument declares which options are supported by your application. This class supports alternative syntax forms for declaring the options. See the sections below for the format and usage of these syntax forms.$_SERVER['argv']
.Zend\Console\Getopt
. See Adding Configuration for reference on the options available.Zend\Console\Getopt
supports a compact syntax similar to that used by GNU Getopt (see http://www.gnu.org/software/libc/manual/html_node/Getopt.html
. This syntax supports only single-character flags. In a single string, you type each of the letters that correspond to flags supported by your application. A letter followed by a colon character (:)
indicates a flag that requires a parameter.$opts = new Zend\Console\Getopt('abp:');
library
', and put 'Zend
' directory in it. Now you should add library to your include path. Edit index.php
file :$includePath = array();
$includePath[] = '.';
$includePath[] = './../application';
$includePath[] = './../library';
$includePath[] = get_include_path();
$includePath = implode(PATH_SEPARATOR,$includePath);
set_include_path($includePath);
$element->setDecorators(array(
array('ViewHelper'),
array('Errors')
));
$element->setDecorators(array(
array('File'),
array('Errors')
));​
$this->getAdapter()->quote();
$select->where(" = ",);
$select->where(" = ? ",);
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
class Foo implements EventManagerAwareInterface
{
protected $events;
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers(array(
__CLASS__,
get_called_class(),
));
$this->events = $events;
return $this;
}
public function getEventManager()
{
if (null === $this->events) {
$this->setEventManager(new EventManager());
}
return $this->events;
}
}
Zend\Escaper
component provides one class, Zend\Escaper\Escaper
which in turn, provides five methods for escaping output. Which method to use when, depends on the context in which the outputted data is used. It is up to the developer to use the right methods in the right context.Zend\Escaper\Escaper
has the following escaping methods available for each context :escapeHtml
: escape a string for the HTML Body context.escapeHtmlAttr
: escape a string for the HTML Attribute context.escapeJs
: escape a string for the Javascript context.escapeCss
: escape a string for the CSS context.escapeUrl
: escape a string for the URI or Parameter contexts.Zend\ServiceManager
component. The Service Locator is a service/object locator, tasked with retrieving other objects. Following is the Zend\ServiceManager\ServiceLocatorInterface
API :namespace Zend\ServiceManager;
interface ServiceLocatorInterface
{
public function get($name);
public function has($name);
}
Zend\Soap\Server
class is intended to simplify Web Services server part development for PHP programmers.Zend\Soap\Server
component works in the WSDL mode, it uses already prepared WSDL document to define server object behavior and transport layer options.Zend\Soap\AutoDiscovery
component or should be constructed manually using Zend\Soap\Wsdl
class or any other XML generating tool.