Posts

Showing posts with the label PHP

Zend Framework 2 model database adapter depedency injection

Typically most of the model classes depend on database adapter. First way to get database adapter instance is to request it via service manager every time you need it. Second, and more convenient one, is to let Zend\Di do all the magic for you. To achieve this you need to implement Zend\Db\Adapter\AdapterAwareInterface in your model class. Or write an abstract class that implements this interface and extend it with your model class and Zend\Di will inject database adapter dependency. Note: to make this work you should instantiate model classes via ServiceManager . How to setup a database adapter is explained in Getting Started with Zend Framework 2 . Abstract class example: <?php //module/<YOUR_MODULE>/src/<YOUR_MODULE>/Model/AbstractAdapterAware.php namespace <YOUR_MODULE>\Model; use Zend\Db\Adapter\Adapter; use Zend\Db\Adapter\AdapterAwareInterface; abstract class AbstractAdapterAware implements AdapterAwareInterface { /** * Database instan

Zend Framework 2 AJAX: return JSON response from controller action. The proper way.

There is a lot of solutions over the web on how to return data on AJAX request in your Zend Framework 2 application. But none of them seems to be aware of the "right way" described in Zend Framework 2 manual - http://framework.zend.com/manual/2.0/en/modules/zend.mvc.examples.html#returning-early Implementation example: <?php namespace <YOUR_MODULE>\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\Json\Json; class AjaxController extends AbstractActionController { public function testAction() { $data = array( 'result' => true, 'data' => array() ) return $this->getResponse()->setContent(Json::encode($data)); } }

Zend Framework 2 navigation menu to array dehydration view helper

Sometimes you need to customize Zend Framework navigation menu output. For instance change <ul><li> output to <div><span>. This is impossible with Zend\View\Helper\Navigation\Menu because its HTML output isn't much customizable (only things like class, indent etc.). Such customization is possible with "partial" script, but my solution is to write a view helper that utilizes navigation menu to array dehydration. Helper: <?php //<YOUR_MODULE>/View/Helper/NavigationMenuDehydrate.php namespace <YOUR_MODULE>\View\Helper; use Zend\View\Helper\AbstractHelper; use RecursiveIteratorIterator; class NavigationMenuDehydrate extends AbstractHelper { protected $container; public function __invoke($container = null) { $this->container = $container; return $this; } public function dehydrate() { $array = array(); $iterator = new RecursiveIteratorIterator($this->getVie

YUI javascript compressor and PHP tags

YUI compressor is very useful and powerful tool for javascript files compression. Many developers compress their static javascript files but what about files with PHP tags? With something like this: var username = "<?php echo $username; ?>"; or like this function() { var some_code_before; <?php if (Acl::check("finance")) { ?> Ext.addShortcut('finance'); <?php } ?> var some_code_after; } First example will work, but YUI will throw an exception on second. And also this piece of javascript code does not pass validation. Lets wrap PHP tags into comments: function() { var some_code_before; /*<?php if (Acl::check("finance")) { ?>*/ Ext.addShortcut('finance'); /*<?php } ?>*/ var some_code_after; } Now this code is valid. But lets try to feed it to YUI: # yui test.js function(){var b;Ext.addShortcut("finance");var a}; PHP tags are stripped away by YUI and

How to dump http request headers with PHP under CGI/FastCGI SAPI

Good old days of PHP installation exclusively as an Apache module are gone. Most of the modern PHP installations interact with a web server via FastCGI protocol. For instance nginx webserver and php-fpm daemon. This means that certain apache SAPI functions are not available anymore. One of this functions is apache_request_headers() to dump http headers sent by client. From CGI specification rfc3875, section 4.1.18: Meta-variables with names beginning with "HTTP_" contain values read from the client request header fields, if the protocol used is HTTP. The HTTP header field name is converted to upper case, has all occurrences of "-" replaced with "_" and has "HTTP_" prepended to give the meta-variable name. According to the specification above i wrote a piece of the PHP code that dumps all headers sent by client under any PHP SAPI: foreach ($_SERVER as $key => $value) { if (strpos($key, 'HTTP_') === 0) { $chunks = e

PHP associative arrays or hashes: in-depth look

Image
Before you start reading i warn you: this article won't help you in every day PHP developing in any way. But if you are naturally interested, like me, in how things work you're welcome to spend your precious time on reading and understanding this article. Still here? Great. Lets try to stay sane after all this low level mumbo-jumbo and start. PHP array or in other terms hash is a combination of the data storing methods called "vector" and "linked list". Vector is a nice aligned structure in the memory, simplest and fastest way to store and access linked pieces of the data because accessing vector offsets functionality is baked right into the modern CPU's. I'm referring to the assembler's offset calculating functionality like MOV [BASE+OFFSET], DATA. Think of the vectors as a numerically indexed PHP array. If you need to access array member you just pass offset to it like this: $array = array("a", "b", "c");

PHP extension development with Linux and Eclipse CDT. Building your environment

Image
It is hard to start with PHP extensions development in Unix environment. It is not enough to be familiar with C programming language also you need at least basic knowledge in packaging, GNU build tools and of course PHP internals. If your desktop is beautified by Linux - there is a good news for you: you don't need to setup and build everything by yourself! You just need to know how to use already configured package for your distribution. Don't even ask what to do if your desktop is crippled by Windows - play minesweeper. This post is intended to give you a good place to start. Everything is shown on example of the Opensuse 11.4, but other distributions are suitable as well. First of all we need to obtain PHP source code. Raw PHP source from php.net can be used but you will need to take care of PHP configuring and all external symbols. Delete stripped php binaries first: # zypper rm php5 next # zypper si php5 this command will download source RPM package and take care o

Curl multi hangs, connection timeout. Asynchronous DNS support

The problem. Curl is a nice library that takes advantage of asynchronous loading. Many developers use CURL in high level languages to load multiple web pages simultaneously. I use curl_multi functions very heavily in my PHP scripts too. But recently i discovered very awkward problem: CURL loads web pages asynchronously but DNS resolution is single threaded! This means that if one of the CURL handles hangs on DNS resolving other handles will hang too and wait for their turn in resolving queue! And if you set curl option "connection timeout" and DNS resolving takes more than timeout you set - all requests will fail! The solution. Starting from version 7.20.0 CURL can handle async DNS resolution using libcares. But cares support isn't enabled by default (at least in Opensuse packages and FreeBSD ports). To take advantage of async DNS resolution rebuild libcurl with --enable-ares option. If your copy of the libcurl is already compiled with async DNS support PHP will repor