Tag Archives: zend

Ubuntu Server: How To Enable OPcache for PHP 7 on Apache Tips, Tricks and Tutorials 23 OCT 2017

PHP is what is known as an interpreted coding language, meaning that unlike compiled apps that have already been compiled down into bytecode (i.e. you have to compile your application first so that the OS can run it), PHP scripts are only compiled and interpreted by the runtime engine on script request.

So, if you have scripts that are relatively static (i.e. you aren’t changing them very often), one good way to accelerate your PHP project is to use some sort of caching system that essentially pre-compiles your scripts down to bytecode, meaning less work come request time and thus theoretically, faster code execution.

Enter opcode caching. OPcache, originally a closed source part of the Zend Server project (under the moniker of Zend Optimizer), is an open source module that stores (caches) precompiled PHP script bytecode in shared memory, thus removing the need for PHP to first load and parse scripts on each request.

Since PHP 5.5.0, the module has come bundled with PHP (though disabled by default), meaning that for all intents and purposes, OPcache is now pretty much the standard when it comes to PHP accelerating.

To set up OPcache on an Ubuntu 16.04 server running PHP 7 over Apache, you first need to enable OPcache via the standard php.ini file. To edit the file:

sudo nano /etc/php/7.0/apache2/php.ini

To enable the module once you have the php.ini file is open, find the line reading ;opcache.enable=0, uncomment it by removing the ; and then enable by changing the 0 to 1:

opcache.enable=1

There are quite a few OPcache related settings that you can change while doing the setup, with the php.ini doing a good job of explaining the role of each one. The important ones to keep track of are: opcache.memory_consumption, opcache.max_accelerated_files, and opcache_revalidate_freq.

Save your changes and then enable the module via:

sudo phpenmod opcache

Finally, restart PHP:

sudo service apache2 restart

Monitoring OPCache is a whole other story (worth a google), but the easiest way just to make sure that it is in fact running is to call phpinfo() on one of your webpages. If enabled, you’ll see a bold section under the title of Zend OPcache, with the first column “Opcode Caching” listing a value of “Up and Running”.

Related Link: PHP OPcache | Wikipedia

Quick way to prevent your Zend Controller from handling a Folder Tips, Tricks and Tutorials 30 JUN 2014

If you have a folder which you need to access in the standard way without your Zend Controller handling it for you (maybe a direct file download outside of your Zend web application), the easiest and quickest way to do this is to simply create a .htaccess file inside the folder you want your Zend controller to ignore and populate it with:

RewriteEngine Off

Because .htaccess files work in a cascading manner, this will overwrite the Zend controller .htaccess file in the root folder, in essence turning off mod_rewrite and thus giving you full control over the folder in terms of Apache now serving it as how it normally would.

zend-zf-logoQuick and easy.

(There are of course loads of other ways to do this, like implementing something like “RewriteRule ^(admin|user)($|/) – [L]” – if you want to ignore folders admin or user – at the top of your main Zend .htaccess file in root, but I like the above as a particularly quick and easy way to simply ignore a specific directory!)

When Your Zend Framework Project returns Page Not Found Errors but Everything is Configured Correctly CodeUnit 29 APR 2011

It can be pretty frustrating. Your Zend Framework project is configured 100% correctly. Mod Rewrite is enabled and working on your server, the .htaccess file is configured correctly and working, all your controllers are correctly created and specified, all with the necessary index actions, your modules are healthy, in short everything is looking 100% like all the examples taught you. Yet for some reason when you try and browse your site, you keep getting Page Not Found, Controller not specified error messages!

I had this issue recently and it was causing me to tear my hair out in frustration. My project was modularized and I was using a menu in the layout, defined in the application.ini file. Everything looked correct and on my Windows dev box all navigation seemed to be working correctly. However, copy the code over to the Ubuntu server and the navigation suddenly broke. Much frustration later, I eventually twigged as to what was wrong. The URLs contained in my menu.

As we all know, camelCase is the default way to express controller and action names in Zend. However, what we do sometimes forget, is that the default URLs are expressed in lowercase, with hyphens indicating the start of a uppercase letter.

In other words while http://myproject/ViewLogs/ may look right to you at first glance, because it matches the name of the controller perfectly, the correct URL is actually http://myproject/view-logs/.

If you remember that, then you shouldn’t go wrong. (Wish I had, to be honest).

So the simple fix was to change the way I specified my menu, from:

resources.navigation.pages.oslo.pages.sub.label = "Allowed Access"
resources.navigation.pages.oslo.pages.sub.module = "oslo"
resources.navigation.pages.oslo.pages.sub.controller = "AllowedAccess"
resources.navigation.pages.oslo.pages.sub.action = "index"

To:

resources.navigation.pages.oslo.pages.sub.label = "Allowed Access"
resources.navigation.pages.oslo.pages.sub.module = "oslo"
resources.navigation.pages.oslo.pages.sub.controller = "allowed-access"
resources.navigation.pages.oslo.pages.sub.action = "index"

And now you know.

Zend Framework: How to Build a Dynamic Layout by Setting Variables in your Controllers CodeUnit 04 APR 2011

I have a Zend Framework website that is broken up into modules. Accordingly, I want my single layout.phtml Layout script to dynamically change ever so slightly depending on what module or rather controller I hit – in my case change the header image. So how do we do this?

Well the first thing is gaining access to the Layout object so that you can set some variables in this.

To gain access within action controllers, use the layout() action helper:

// Calling helper as a method of the helper broker:
$helper = $this->_helper->getHelper('Layout');
$layout = $helper->getLayoutInstance();

To gain access within view scripts, use the layout() view helper:

$layout = $this->layout();

To gain access via the bootstrap, retrieve the layout resource:

$layout = $bootstrap->getResource('Layout');

Finally if you still can’t get a layout object to work with, use the static method (not entirely recommended):

$layout = Zend_Layout::getMvcInstance();

Now that you have a $layout object to work with, you’ll probably want to assign some sort of variable value to it in order to dynamically affect your layout.phtml file. To set a variable you can either directly assign with the = operator or make use of the assign() method:

// Setting content:
$layout->somekey = "foo"
 
// Using the assign() method:
$layout->assign('someotherkey', 'bar');

Okay, now that we have a variable stored in the layout object, it becomes trivial to make our layout dynamic. For example, having previously added a value to $layout->mainheaderlogo = ‘image1.png’, we can now add the following to our layout.phtml file:

<div id=”logobanner”><a href=”/”><img src=”/images/<?php echo $this->layout()->mainheaderlogo; ?>” /></a></div>

And now you know. Nifty.

(Update: Or you should probably really learn to use Zend View Placeholders correctly, as they are the correct way of making your layout more Dynamic!!)

How to Create a Zend Framework Project that Uses Modules CodeUnit 01 APR 2011

If your website can be logically split into a number of different functionalities, it makes sense to group those functionalities accordingly. In Zend terminology we are talking about modules, literally the folder splitting of logically grouped pieces of functionality. However, by default a generated Zend Framework project isn’t modular and to get the thing properly modularized, here’s what you have to do.

Using Zend Framework 1.11.4:

First, create your project like you normally would via the command line interface:

zf create project moduleproject
cd moduleproject

Next, create your default module. This will house module that will handle all requests to the root of your site, in other words http://moduleproject/helloworld or http://moduleproject/

zf create module default

Now add the all important index and error controllers:

zf create controller Index index-action-included[=1] default
zf create controller Error -m default

Replace the contents of the generated error controller with the following contents: (c:moduleprojectapplicationmodulesdefaultcontrollersErrorController.php)

class Default_ErrorController extends Zend_Controller_Action
{

    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');
        
        if (!$errors || !$errors instanceof ArrayObject) {
            $this->view->message = 'You have reached the error page';
            return;
        }
        
        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()->setHttpResponseCode(404);
                $priority = Zend_Log::NOTICE;
                $this->view->message = 'Page not found';
                break;
            default:
                // application error
                $this->getResponse()->setHttpResponseCode(500);
                $priority = Zend_Log::CRIT;
                $this->view->message = 'Application error';
                break;
        }
        
        // Log exception, if logger available
        if ($log = $this->getLog()) {
            $log->log($this->view->message, $priority, $errors->exception);
            $log->log('Request Parameters', $priority, $errors->request->getParams());
        }
        
        // conditionally display exceptions
        if ($this->getInvokeArg('displayExceptions') == true) {
            $this->view->exception = $errors->exception;
        }
        
        $this->view->request   = $errors->request;
    }

    public function getLog()
    {
        $bootstrap = $this->getInvokeArg('bootstrap');
        if (!$bootstrap->hasResource('Log')) {
            return false;
        }
        $log = $bootstrap->getResource('Log');
        return $log;
    }


}

Next create an error view that will be used by Error controller: (c:moduleprojectapplicationmodulesdefaultviewsscriptserrorerror.phtml)

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Zend Framework Default Application</title>
</head>
<body>
<h1>An error occurred</h1>
<h2><?php echo $this->message ?></h2>

<?php if (isset($this->exception)): ?>

<h3>Exception information:</h3>
<p>
<b>Message:</b> <?php echo $this->exception->getMessage() ?>
</p>

<h3>Stack trace:</h3>
<pre><?php echo $this->exception->getTraceAsString() ?>
</pre>

<h3>Request Parameters:</h3>
<pre><?php echo $this->escape(var_export($this->request->getParams(), true)) ?>
</pre>

<?php endif ?>

</body>
</html>

Finally, add the following line in the production section of your application.ini file: (c:moduleprojectapplicationconfigsapplication.ini)

resources.modules[] =

Set your environment so that errors are display and then first hit your project URL to make sure it is showing up correctly, i.e. http://moduleproject/. Next, hit a non-existent URL like http://moduleproject/fail and look at the resulting error page. If the request parameters reads array( … ‘module’ => default’ … ) then you’re finished.

You now have a completely modularized project, which you can add to by running

zf create module module2
zf create controller index -m module2

Nifty.

How to create Menus and Breadcrumbs in Zend Framework using the Config .ini File CodeUnit 30 MAR 2011

To create navigation menu items in the Zend Framework by storing all the information in your config application.ini file turns out to be a relatively simple affair.

First add the following line to your application.ini file:

resources.navigation.storage.registry[] = 

Next define your pages as follows:

resources.navigation.pages.home.label = "Home"
resources.navigation.pages.home.controller = "index"
resources.navigation.pages.home.action = "index"

resources.navigation.pages.item2.label = "Next Item"
resources.navigation.pages.item2.controller = "nextitem"
resources.navigation.pages.item2.action = "index"

;for modules try:
resources.navigation.pages.home.label = "Home"
resources.navigation.pages.home.module = "admin"
resources.navigation.pages.home.controller = "index"
resources.navigation.pages.home.action = "index"

;for sub menu items:
resources.navigation.pages.home.pages.sub.label = "Sub1"
resources.navigation.pages.home.pages.sub.controller = "sub"
resources.navigation.pages.home.pages.sub.action = "index"

Now that your pages have been defined, your bootstrap file can be used to initiate the layout, which in turn initiates the navigation object automatically. If you check your bootstrap file, you should have a function looking something like this:

protected function _initNavigationConfig()
    {
    $this->bootstrap('layout');
    $layout = $this->getResource('layout');
    $view = $layout->getView();
    }

Finally, to actually print out the navigation menu in your layout, simply add the following line somewhere in your layout.phtml file:

$this->navigation()->menu();

As easy as that.

Note that if you want breadcrumbs in your layout, you can use this:

echo $this->navigation()->breadcrumbs()
->setLinkLast(false)->setMinDepth(0)->render();

Nifty.

Zend: How to fix the 404 Problem in a Zend Framework Project CodeUnit 23 MAR 2011

If you have a nice and shiny new Zend Framework project all set up but are still getting nasty browser 404 errors when attempting to hit URL other than the home page (instead of the expected errors dealt out by the error handler controller), the root of your problem is actually quite simple:

Your Apache mod_rewrite module is disabled and your Apache directory AllowOverride directive is not switched on.

To fix is easy enough. Locate your Apache httpd.conf configuration file and open it up. Run a search for mod_rewrite and you should find the line:

#LoadModule rewrite_module modules/mod_rewrite.so

Uncomment it in order to enable, by removing the # character from the front of the line.

Next search for AllowOverride and you should find it in one of your declarations. If it is present, change the value to All. If it isn’t, add it. (Note if you are using virtual hosts you will need to set it under the virtualhost declaration). Setting this to all means that Apache will honour local .htaccess files, which is exactly what Zend, in conjunction with mod_rewrite, depends on.

Restart Apache, and hit a non home page URL.

And now you know.

Worth Reading: Zend Framework in Action (Rob Allen, Nick Lo, Steven Brown) CodeUnit 18 MAR 2011

Let me start off if you want to learn to program, or learn to program in PHP specifically, you don’t learn by starting off using a framework. That is not going to teach you anything other than making you unable to solve small problems in the most efficient manner.

However, if you are already a programmer and have been asked to pick up Zend, the first thing you’ll find is that the learning curve into Zend is steep. Very, very steep.

So much so that there is no way a bunch of simple tutorials are going to get you properly versed in the framework, leaving us in other words with proper learning materials – i.e. books.

And if you are looking for a good book, look no further than the excellent Zend Framework in Action by Rob Allen, Nick Lo and Steven Brown, published by Manning.

In depth, covering all aspects of the Zend Framework in an easy to understand manner, padding out with a lot of examples (and more importantly, a nice complex real world website that gets carried throughout the text), Zend Framework in Action is an excellent read to get you properly up and running and well on your way to becoming proficient in the world of Zend.

Nifty.

How to Create a Zend Project from the Command Line with zf Tips, Tricks and Tutorials 16 MAR 2011

To generate an empty project shell using the Zend Framework is pretty easy thanks to the powerful zf command line utility.

To create a project, simply open a command line window, browse to the directory in which you want to create your Zend Framework project and enter:

zf create project "My Project"

zend-zf-logowhere My Project is the name of the project you want to generate. Note that for project names containing spaces, you can make use of double quotes to enclose. Also, zf (or rather the Zend bin directory) should be added to your system PATH in order to give it global visibility and thus make it easier to use.

The program will create a directory matching the name of your given project, and populate it with all the necessary Zend shell structures. You should at a minimum have application, docs, library, public and tests folders in the root, as well as a .zfproject.xml file. In the public folder, check that there is a .htaccess file containing the following rules:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Finally, you need to either symlink the library folder to that of the installed Zend framework’s library folder on the system, or just copy the Zend framework library folder’s contents into the library folder of your new project directory.

Done.