Category: PHP

Installing the memcached PHP module for PHP 7 on Plesk

To install the PHP memcached module for PHP 7 on a Plesk 12.5 server running CentOS 6.8. Please note that this should also work on CentOS 7. We’re going to need to install the libmemcached dev package first: sudo yum install -y libmemcached-devel Next install the PHP 7 dev package. Since this is a Plesk server we install the Plesk version of this package: yum install -y plesk-php70-devel After installing these, cd to a temporary directory and clone the memcached module git repo and checkout the php7 branch: cd /tmp git clone git checkout php7 Next build the memcached module. Make sure to use the PHP 7 version of phpize and point to the PHP 7 version of php-config in the configure command: /opt/plesk/php/7.0/bin/phpize ./configure --disable-memcached-sasl --with-php-config=/opt/plesk/php/7.0/bin/php-config make sudo make install The module has been built and installed now. Now you only have to enable it: cd /opt/plesk/php/7.0/etc/php.d echo "" > memcached.ini Finally restart the webserver for the changes to take effect: sudo apachectl restart To make sure the module is loaded you can run: /opt/plesk/php/7.0/bin/php -m memcached should show up in the list of ...

(Read more...)

ZF2 routes with parameters containing slashes

The routing system of ZF2 is pretty flexible, which is nice in case you need something custom like I did today. I needed to be able to handle some Base64 parameter data and so it’s possible that this data will contain slashes. Therefore a plain vanilla segment route like this won’t work: 'my-route' => array( 'type' => 'Segment', 'options' => array( 'route' => '/myroute/:encdata', 'defaults' => array( 'controller' => 'Application\Controller\MyController', 'action' => 'handle-enc-data', 'encdata' => null, ), ), ), When my URL would be something like this the route wouldn’t be matched because of the slash characters inside of the Base64 parameter: http://my.local/myroute/c3ViamVjdHM/X2Q9MQ== A regex route can solve this problem. It’s actually pretty simple: 'my-route' => array( 'type' => 'regex', 'options' => array( 'regex' => '/reg4p/(?.*)', 'spec' => '/reg4p/%encdata%', 'defaults' => array( 'controller' => 'Application\Controller\MyController', 'action' => 'handle-enc-data', 'encdata' => null, ), ...

(Read more...)

Events, the EventManager and ListenerAggregates in Zend Framework 2

There are a bunch of good articles on this subject on the web already, but for my own reference I put together this article listing the steps to take to set up your own custom event listeners in your ZF2 application. Start by creating a class handling the events. This class will implement the Zend\EventManager\ListenerAggregateInterface. In this example I will create a listener aggregate that takes care of sending out e-mails for different events. I like to keep my listener aggregates to be groupings of related actions in response to events. For example I would have a LogEventsListener listening to the ‘runtime_error’ event. The handler for this event would for instance make a log entry of what went wrong. At the same time I would have a MailEventsListener also listening to the ‘runtime_error’ event and send out an e-mail to the developer or administrator when a fatal error occurs in the application (random example). Besides the ‘runtime_error’ event there could be other events that either the LogEventsListener or MailEventsListener deal with. So back to the code the MailEventsListener could look like this. MyApp\Listener\MailEventsListener.php:   <?php namespace MyApp\Listener; use Zend\EventManager\EventInterface; use Zend\EventManager\EventManagerInterface; use Zend\EventManager\ListenerAggregateInterface; use Zend\ServiceManager\ServiceLocatorAwareTrait; use Zend\ServiceManager\ServiceLocatorAwareInterface; use MyApp\Config\ConfigAwareTrait; use ...

(Read more...)

Database Testing with PHPUnit

Disclaimer This post is mainly meant for my personal future reference, but I thought it may be useful to other people too. So it’s not an extensive guide for using DBUnit, but more of a step-by-step list of how to get started using it. Introduction I am currently working on a small PHP project using the Silex framework, or mini-Symfony if you like. It consists of three parts: a RESTful web service (based on Silex), a cron job (also based on Silex) and a JavaScript heavy front-end.¬†The RESTful service is what I’m currently working on and for which I needed some more extensive database testing. The problem The RESTful service project consists of some controllers, which are responsible for handling the available actions that the service is able to perform. For the actual work there is a Service layer and the controllers delegate the heavy lifting to the services in that layer. So even though there are some simple tests for each of the actions in the controller, the services are the most difficult to test since they are data-heavy. For some of the methods a simple mock db adapter returning some mock data was sufficient, but when you really ...

(Read more...)

Sending e-mail with alternative parts plus attachments

Today I was working on my MailService component in a ZF2 project. For this specific project I needed to be able to support alternative parts for text and html combined with attachments. The alternative parts are to allow less sophisticated mail readers, not capable of rendering html, to still read the message. When sending mail using the Zend\Mail\Message class you have to create a Zend\Mime\Message object and assign this object to the body of Zend\Mail\Message, using setBody(). The Zend\Mime\Message object contains the actual parts of the message and the Zend\Mail\Message is responsible for the mail headers. The default content-type of a Zend\Mail\Message is 'multipart/mixed'. This is usually perfect if you're only sending one text part and optionally one or more attachments, but if you want to support alternative parts (requires content-type 'multipart/alternate') AND attachments (requires 'multipart/mixed') then you have a little ...

(Read more...)

Adding custom fields to ZfcUser register form

The ZfcUser module ZfcUser is a Zend Framework commons module that handles basic use cases related to users. It takes care of handling the registration, logging in, logging out, authenticating and user profile management. It is a very well written module, allowing the user of the module to change the behavior without having to hack in the module’s codebase. Tip: never change the code of a vendor module. The problem A common use-case for the ZfcUser module is to add more fields to the registration form (i.e. a firstname and lastname or date of birth). Of course when I needed this functionality myself, I did a quick search and figured I wasn’t the only one needing this. However there were no real¬†conclusive answers of how to do this. I did find one article[1] that helped me to get started. What I needed What I needed was the following: Add the extra fields to the registration form; Make sure the fielddata gets saved to the database when the user registers; Adding validators and filters to the custom fields; Changing the validator messages of the standard ZfcUser userfields; Changing the order of the fields in my registration form. How I accomplished it ...

(Read more...)

Dealing with alternative directory structures in ZF2

I just started diving into Zend Framework 2 after using Zend Framework 1 and even its early predecessors for years. And boy, things have changed! But after some initial reading I think I already see some major advantages, not in the last place the ModuleManager which really allows developers to create independent modules and share them with the community. Anyway on to the actual subject of this post: directory structure. A standard ZF2 application has the following directory structure: config data module public vendor init_autoloader.php public contains index.php and your .htaccess, plus your public web resources such as images javascript and css files. In a shared hosting environment running Plesk the directory structure is like this: httpdocs (this is the webroot) private statistics subdomains etc. We don’t want to put everything in the httpdocs directory, because that’s the public directory and is accessible from the outside world. In a Plesk environment the private directory is used for application level files that aren’t supposed to be accessible from outside. So the solution is pretty simple: Upload the contents from the public directory into httpdocs Upload the other directories (config, data, module, vendor and init_autoloader.php) into private After that you have to ...

(Read more...)

Using Zend_Crypt_Rsa – small example of how to use it

PHPMay 05 20120 Comment

For a recent project I needed to use RSA encryption to encrypt some sensitive data that was being sent from a client to a (JSON) service. Both the client and the service are written in PHP using Zend Framework, so the obvious place to look for classes implementing this functionality is… well the Zend Framework library of course. I was happily surprised finding the class Zend_Crypt_Rsa in the Crypt folder of the Zend Framework. When I wanted to check the online documentation at I was less happy, because it turns out there is no documentation for this class. Luckily it’s really not that hard to use. If you check out the code of the class itself it’s pretty self explanatory. However to save someone else some time it might be useful to post the steps I took to get it working, so here we go. 1. First of all you will need to have OpenSSL installed and the openssl PHP extension loaded, because the Zend_Crypt_Rsa class is dependent on it. 2. You have to generate the private and public keys that you’re going to use for the encryption (public key) and decryption (private key). You do this using the ...

(Read more...)

Datamapper pattern in PHP

PHPSep 19 20110 Comment

The object-relational gap is a general problem in every OO programming language. Since PHP joined the OO club a while ago this problem also came along with it. What I mean by object relational gap is the difference between a row in a relational database and an object in an OO language. Even though they have a lot in common, they aren’t the same thing and an OO programmer has to solve this by mapping rows to real objects. In an ideal world a programmer would only be concerned about objects and not database queries (and all the details that come with it) and many smart people have been trying to find the perfect solution to realize this. The result is many persistency frameworks that require the programmer to meta-tag class attributes to map them to database columns or write schemas to do the mapping. Some examples include JDO, JPA, (N)Hibernate, PDO and so on. In my opinion at this moment Microsoft offers the best solution with Linq, because it truly became part of the programming language and the programmer only has to deal with objects, while syntax checking happens at programming/compile time instead of runtime. Hopefully other languages (including ...

(Read more...)

Parsing XML using DOMDocument and DOMXpath

PHPSep 06 201112 Comments

In many webprojects I need to parse XML files of different kinds and shapes. PHP offers the DOMDocument class and the SimpleXML extension to read, parse, query and create XML documents. I personally prefer using the DOMDocument class hierarchy to SimpleXML, because it’s more powerful and offers more functionality especially when it comes to creating XML documents. To show some possibilities of those classes I will demonstrate how to use them to parse Excel XML data. Here’s a screenshot of a small demo Excel workbook (a fictive pricelist): You can save any Excel file in Excel XML format using Save As… and selecting XML Spreadsheet 2003 (*.xml): After saving it to an XML file, the XML will look like this: I collapsed the first few elements, because I’m going to focus on parsing the actual Worksheet data in this example. So lets say you’re interested in parsing the cell data of this Excel sheet. If you only want to perform simple queries on your XML document the DOMDocument methods will suffice. In this case where you only want to get all Cell elements you could use the getElementsByTagName method, i.e.: $xmlFile = 'pricelist.xml'; $domDoc = new DOMDocument(); $domDoc->load($xmlFile); $cells = ...

(Read more...)