Clear the Field of an non-Editable AngularUI Typeahead

When working with non-editable AngularUI Typeaheads (i.e. ones that have the typeahead-editable attribute set to false), a logical thing to do would be to erase the typeahead input field’s view value if the user doesn’t select a valid typeahead option. However, there’s no built-in option to do just that, so here’s a workaround.

The main idea here is to use the ng-blur attribute to set a function that will clear the typeahead field if no valid option was selected. To do that first we need to access by name the form controller object containing the typeahead. If the typeahead is not contained in a form element, what we can do is declare one of its parent elements as a form controller using ng-form, and give names to both of them:

<div ng-form name="myForm">
<input type="text" name="myField" ng-model="myField" ng-blur="clearUnselected()" typeahead="myField in myFields" typeahead-editable="false" />
</div>

Now we can access the the typeahead’s form properties from the AngularJS controller, and reset its $viewValue property if no valid option was selected by the user. We wrap this into an AngularJS $timeout because there’s a delay between clicking on an option and the corresponding model updating. Don’t forget to inject the $timeout service into your controller!

//inside your controller
$scope.clearUnselected = function () {
$timeout(function () {
if (!$scope.myField) { //the model was not set by the typeahead
$scope.myForm.myField.$setViewValue('');
$scope.myForm.myField.$render();
}
}, 250); //a 250 ms delay should be safe enough
}

PrestaShop Module Development by Fabien Serny – a book review

This book, written by one of the original members of the Prestashop developer team, is an invaluable resource for anyone whose income depends at least in part on developing Prestashop modules. The time savings alone, as compared to having to browse through the Prestashop classes and native modules just to find how an example of functionality similar to what you require, are definitely worth the price of admission.

The book outlines Prestashop best practices, goes into detail on the different types of modules, and describes the usage of helper form and list classes, the context object, overrides, and how to handle module updates. Part of this information can be also found in Prestashop’s developer guide, however the book goes into much more detail and lays out quite explanatory code samples. However, the most useful part of it all might be the Native Hooks Appendix, which has a list of all the 145 native hooks (as of Prestashop 1.6) with their descriptions, parameters, and the files they are called from.

As for stuff missing from the book, I believe a section on Functional Testing of modules would have been really useful, since the Prestashop developer community would surely benefit from incorporating automated testing into its development standards. Apart from this, the book’s a real time saver if you’re a Prestashop beginner, and even if you’ve got quite a few modules under your belt, it should at least help to improve the quality of your code.

Get data from a Jet DB (Microsoft Access) file in Windows using LibreOffice

If you need to access data from a Jet DB file, there’s a relatively simple way to do it in Windows without Microsoft Office, by using LibreOffice and creating an ODBC data source.

First open your Windows/SysWOW64/ folder in explorer and run odbcad32.exe as Administrator. The ODBC Data Source Administrator should open. Once it does, stay on the User DSN tab and click the Add button. Select the Microsoft Access Driver and click Finish. On the new window that will open write the name of your file (or anything you want, for that matter) in the Data Source Name field, next click on the Select button of the Database subsection, and select your file. Click OK to close both windows.

Now that the data source is set up, open Libre Office Base, select Connect to an existing database, and select ODBC in the dropdown menu. Click on Browse, choose the data source you just created, and click OK. Click on Finish and save your config as a new file. Now you should have access to all of the database tables in the file.

This method has the disadvantage of requiring you to create a new ODBC data source for each file you need to open, but it sure beats all other ways I’ve found so far that don’t require using a suitable version of Microsoft Access.

How to fix blank screen in Preferences > Themes on the Prestashop Back Office

The Symptoms

You’ve linked your shop to your Prestashop Addons account, where you’ve previously or recently bought a theme. You try opening the Preferences > Themes menu, just to find that after trying to load the page for a while, you either get a blank page (even with dev mode on) or a cryptic 500 error.

The cause

When the Admin Themes Controller initializes, it checks if you’re logged into Prestashop Addons, and if so, whether there’s a theme in your account that hasn’t been installed in your store. If there is, it tries to download it automatically, and here’s where the problem lies: your server is timing out during this connection. If you go to your server error log, you’ll probably find an error such as mod_fcgid: read data timeout in xx seconds if your PHP installation is running on FastCGI.

The Solution

Unfortunately, if you are running on a shared host you almost certainly won’t have the required access necessary to change the server’s timeout parameters. In that case the only course of action is to disable the theme auto-download functionality in AdminThemesController.php, and this can be cleanly done in an override. This is all the code you need in your override:


<?php
class AdminThemesController extends AdminThemesControllerCore
{
    public function init()
	{
        $this->logged_on_addons = false;
        parent::init();
	}
}

If you don’t know how to create overrides don’t worry, you can download the following zip with the override already in place. All you need to do is extract the folder within, upload it into your store’s root Prestashop folder, and delete the file cache/class_index.php on your store so the override is detected.

PHPUnit Essentials by Zdenek Machek – a book review

(Disclosure: I received an advance copy of this book from Packt Publishing for review purposes.)

The more complex a software development project becomes, the harder it becomes to ensure that every single component keeps working as it should throughout the whole development process. As each passing year the average complexity of software goes up, automated testing is slowly becoming the most cost effective way to reign in some of that complexity. By providing reassurance that the latest changes to the code did not break existing functionality, it allows for quicker iterations, higher code quality, and less time wasted in debugging. As the de-facto standard in unit and functional testing for PHP, PHPUnit is increasingly becoming an indispensable part of the web developer’s toolkit, and PHPUnit Essentials by Zdenek Machek is a pretty solid introduction to it for intermediate-level PHP developers.

The book is effectively about 300 comfortably spaced pages, divided into 14 chapters. It has a rather broad scope, covering not only basic PHPUnit installation and usage, but also related interoperable technologies such as advanced test doubles extensions, Selenium (for web browser testing), XDebug (for code coverage analysis), Continuous Integration services, and even IDE support for some popular PHP IDEs. For me this wide scope is one of the two great strengths of this book; since web developers never work in a vacuum, chances are that if you’re learning to use PHPUnit, sooner or later you will also need to learn how to use some of the complementary technologies described in this book. While it might not go into the greatest detail with most of them, it will at least teach you to set them up, integrate them with PHPUnit, and their basic usage.

The other great strength of this book is that it explains, in an easy to understand manner, some more advanced concepts such as different types of test doubles, database testing, and how to test legacy (a.k.a. “untestable”) code. The chapter on legacy code stands out as it provides some very useful approaches to introduce automated testing to the type of code that needs it the most.

As for weaknesses, my main complaint would be that the book sometimes fails to go into enough depth in some topics. The biggest omission would be an overview of all, or at least most, of the PHPUnit annotations and assertion methods. I know the official PHPUnit documentation already includes that as an appendix, but it would be nice to have it here at least in a table with short descriptions as a reference. Also, running PHPUnit on a remote server, as opposed to localhost, is not really explored outside of Continuous Integration services (which basically do that for you), and BDD is only explored through other testing frameworks or extensions. Finally, as far as complaints go, mentioning how “Codeception is really awesome… but we’re not going to write about it”, at the summary of the very last chapter, made me feel a little bit cheated.

Overall, the writing style is easily understandable, though at times it can feel a little bit redundant. The good thing is that it doesn’t make you backtrack to look at previous code like some other very frustrating books out there (I swear, it’s as if their authors have never used a tablet or eReader to read an ebook in their entire lives). It may fail to go into enough detail in a couple of places, but the simple explanations of advanced testing concepts, along with the discussion of useful related technologies, make PHPUnit Essentials a quite solid introduction to not only PHPUnit, but the world of TDD as a whole.

Access Private and Protected Properties of Objects in PHP

The theory goes that forcibly overriding Class behaviour from outside its scope is bad practice. However, in the real world we developers often times find ourselves having to adapt to, or work on top of, existing code outside of our control. That’s where hacks like these come in handy, though you should really use them with caution, and always because there’s no other choice available.

The Array Cast Override

This is the conceptually simplest method I’ve found, and the only one I know that works on PHP versions previous to 5.3. It involves casting an Object as an Array, and looking through the Array elements for the property you need. When doing this, the index of the Array element corresponding to each property is named according to special rules, depending on its visibility inside the Object. The next pseudo-code snippet shows these rules:

switch ($visibility) {
case 'public':
$array_index = $property_name;
break;
case 'protected':
$array_index = "\0*\0" . $property_name;
break;
case 'private':
$array_index = "\0" . $class_name . "\0" . $property_name;
break;
}

This means that the way you access the property depends on its visibility. As you can see PHP sandwiches either an asterisk or the Class name (depending on if the visibility is protected or private, respectively) between two NULL bytes, and prepends this to the property name to form the Array index. You can thus access the hidden properties of an object as follows:

class MyExampleClass //example of a class with hidden properties
{
public $myPublicVar = "I'm public!";
protected $myProtectedVar = "I'm protected!";
private $myPrivateVar = "I'm private!";
}

$obj = new MyExampleClass();
$obj_array = (Array)$obj; //cast the object as an Array

echo $obj_array['myPublicVar']; //echoes: I'm public!
echo $obj_array["\0*\0" . 'myProtectedVar']; //echoes: I'm protected!
echo $obj_array["\0" . 'MyExampleClass' . "\0" . 'myPrivateVar']; //echoes: I'm private!

The type of the property doesn’t matter, I’ve even accessed resource handlers this way.

The Reflection Override (PHP >= 5.3)

When talking about overriding a property’s visibility, this is the method most seasoned developers know. Using the Reflection Class, you reflect an existing object and change the accessibility of each property you need by using the ReflectionProperty::setAccessible method. Here is an example:

class MyExampleClass //example of a class with hidden properties
{
public $myPublicVar = "I'm public!";
protected $myProtectedVar = "I'm protected!";
private $myPrivateVar = "I'm private!";
}

$obj = new MyExampleClass();
$refObj = new ReflectionObject($obj);
$refProp1 = $refObj->getProperty('myProtectedVar');
$refProp1->setAccessible(TRUE);
$refProp2 = $refObj->getProperty('myPrivateVar');
$refProp2->setAccessible(TRUE);

echo $refProp1->getValue($obj); //echoes: I'm protected!
echo $refProp2->getValue($obj); //echoes: I'm private!

Using Reflection is supposedly really slow, but the upside is that you can not only read the value of the property, but also change it using the ReflectionProperty::setValue method.

The Closure Bind Override (PHP >= 5.4)

This is the newest method I’ve come across, and it’s also the quickest and most painless one. It uses the bind static method of the Closure class to bind a Closure to our Object, which we’ll use to return the properties we want. The usage is really straightforward:

class MyExampleClass //example of a class with hidden properties
{
public $myPublicVar = "I'm public!";
protected $myProtectedVar = "I'm protected!";
private $myPrivateVar = "I'm private!";
}

$obj = new MyExampleClass();
$propGetter = Closure::bind( function($prop){return $this->$prop;}, $obj, $obj );

echo $propGetter('myProtectedVar'); //echoes: I'm protected!
echo $propGetter('myPrivateVar'); //echoes: I'm private!

It works almost like magic, the disadvantage being that most shared hosting providers are lazy and haven’t bothered to update their PHP versions since the Late Pleistocene. If you can use it, this is the method I would recommend the most.

Do you know any other methods to access hidden properties of objects? If so, I would love to read you comments below.

Acknowledgements and References

fmmarzoa at librexpresion dot org
Tobias Schlitt
PHP.Net