The well written code is also testable code – it is loosely coupled to the other components, it follows the single responsibility principle, there are no explicit dependencies and so on. We all know the rules, but there is always an exception.
It’s pretty common situation to unit test component or controller that depends on another core Yii component – for example using \yii\web\Request to get query string or $_GET variable.
Rewriting your library in order to remove the explicit dependencies is not always option, because it may lead to massive refactoring and actually break more things than benefits.
In such as case a what I really want to do is to assign temporarily \Yii::$app->request PHPUnit Mock Class, so I can override the return values e.g.
$request = $this->getMock('\yii\web\Request', ['getUserIP', 'getUserAgent', 'getBodyParams']);
->will($this->returnValue('Dummy User Agent'));
There are few methods of redirecting to referer.
Inside your controller action you can use:
Alternatively you can write it like this:
$request = $this->getRequest();
Lately, I’ve been working on transitioning XML feeds to JSON format on big video site. We generate these feeds in order to feed external search service with results. It’s similar to sitemap, but it provides more detailed information about the pages.
This task is challenging because of the following problems that need to be resolved:
- The feed need to represent over 500 000 database entries i.e. videos. It’s just not possible to generate huge PHP multidimensional array with more than 500 000 elements and pass it to json_encode(). Obviously, you need to generate small JSON objects (chunks) concatenated with hand-coded strings and so build the full feed.
- The development and production servers we use are equipped with outdated PHP version 5.3.27. That means:
– No meaningful error messages because json_last_error_msg() function it’s not available prior PHP 5.5
– No JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE
- The code should be easy to test and maintain, so it should provide meaningful debug information and error handling.
Continue reading “Generate huge JSON files with custom PHP >5.3 class” »
As a PHP developer you know that it’s common task to check how long a particular class, function or procedure performs. Usually this involves measuring of the time particular code snippet takes to execute. There are lots of PHP code benchmark scripts out there, but the simplest method remains to check the difference between the start and end time. Continue reading “Format microtime() to provide better feedback on the time elapsed” »
I just have released Browser – PHP port of the popular jQuery browser plugin. It can detect browser name, version and platform. Additionally, mobile and desktop browsers are recognized. It is pretty simple and lightweight to use.
I would be glad to receive any feedback from you!