/usr/portage

Not having globals state doesn't mean you're doomed 11

Clear Dependencies
hbp_pix©

A pretty popular myth about avoiding global state (singletons, multitons, registries, global variable, static variables/methods) is that it results in creating widely used objects more often than needed. The most common example in this case is a database connection. We try to avoid global state to let objects express their dependencies clearly: the object constructor should be as readable as “give me this, give me that and I will work”. Let’s talk about a situation where we instanciate a relatively complex set of domain objects including a service layer. For the example, we assume that we read an existing customer. We use the CustomerServiceLayer to retrieve the Customer, which uses the CustomerRepository to create the Customer object which needs a DatabaseConnection connection and passes a strategy (NameFormattingStrategy) to format the name of the customer to the Customer object and a CustomerDataMapper to allow the Customer object to save itself. Here are the constructor signatures of the involved components:

class Customer ...
    public function __construct(
        NameFormattingStrategy $nameFormattingStrategy
    )
class CustomerRepository ...
    public function __construct(
        DatabaseConnection $connection,
        CustomerDataMapper $dataMapper,
        NameFormattingStrategy $nameFormattingStrategy
    )
class CustomerServiceLayer ...
    public function __construct(CustomerRepository $repository)
class CustomerDataMapper ...
    public function __construct(DatabaseConnection $connection)
class DatabaseConnection ...
   public function __construct(
       string $host,
       int $port,
       string $username,
       string $password,
       string $database
    )

So, all we do in the page controller, may it be a (page) controller or a plain PHP file is instanciating the service layer and its dependencies:

$databaseConnection = new DatabaseConnection(...);
$customerDataMapper = new CustomerDataMapper($databaseConnection);
$nameFormattingStrategy = new NameFormattingStrategy();
$customerRepository = new CustomerRepository(
    $databaseConnection,
    $customerDataMapper,
    $nameFormattingStrategy
);
$serviceLayer = new CustomerServiceLayer($customerRepository);
$customer = $serviceLayer->getCustomerById((int)$_GET['customer_id]);
... pass it to the view, do nifty things ...

If other components, like the OrderRepository needs a database connection, just pass it to it. No need to let the order repository know how to get it. It is just there. In your unit test you can passed a mocked repository, a mocked database connection and a mocked data mapper depending on what particular part of the chain you are going to test. By the way: the heavy construction work could be easily passed to a number of factories just responsible for creating your objects. These factories are easily testable too as the only assertion made would be is the returned object correctly configured.

Filed under , , , & eleven comments & no trackbacks

New languages to broaden my horizon 6

I’ve read a bit and played around with Scala and Arc recently. I always recommend to learn other languages. Nobody is forced to get productive tomorrow in a language one learns but it always makes you a better programmer. This sounds trivial but I often met programmers who did only Java or only PHP or … you name it. There is nothing wrong with focusing on a language and getting really good at it, but ignorance is wrong. A good programmer always wants to learn, he basically defines himself through his fast ability to adopt new stuff. Everytime I look at different languages outside of my daily scope (which is mostly PHP and C, Ruby and Python for fun), especially on those who look exotic from the first view, I get something better. When I’ve tried to learn Erlang – even I totally failed at really getting it – I looked completely different afterwards at PHP constructs like array_filter(), array_walk() and the general concept of callbacks. When you halfway know both worlds, the functional as well as the object oriented, you just get more effective in applying the adequate methodology to solve an issue.

Back to Scala. Scala comes with a really feature rich object model. It provides classes, a concept well known to those who do Java or C++. Classes and methods may even be abstract. So far nothing new. But Scala provides a language feature so called traits. It addresses the issue that single inheritance is often too limited when it comes to stable (and convenient) compositions while mixins as in Ruby or classical multiple inheritance as in Python induce fragile, hardly maintanable hierarchies. The answer are traits. Traits allow stable compositions. A trait is basically a container for functionality. A class may extend from multiple traits, rename or overrride methods. Think on a debugging functionality – in this case implemented as a debugging trait – which should be used in a number of classes while each class has its own hierarchy. The debugger is than easily composited with the debugging consumer class while the class hierarchy is kept and the composition is stable itself. In PHP we do big wrenches to do composition. We introduce broker components to handle composited objects and what not. Traits are an elegant solution to the problem, a really impressive language construct.
Scala also provides generics. Generics are datatypes that can take other types while keeping type safety. Think you have an array and can enforce it to only accept instances of the class “Foo”. C#, Java and C++ implement that concept for a long time but nevertheless it is really handy.
I’m not really sure, how handy that would be in practice, but Scala enforces to explicitly overrride methods. I have the feeling that after a while one would do “override def method()” with the same implicitness as we do it today. Maybe this feature will be good for teaching object oriented programming.
The general syntax is a best of both worlds, the Java and the Ruby world. It is also possible to reuse existing Java libraries in Ruby, which makes it pretty attractive and lowers the entry barrier as a full stack of libraries are already present.

Arc is the newest baby by Paul Graham, the inventor of the bayesian spamfilter which mildens the pain for everyone of us dealing with email. Graham loves Lisp and it relatives. This is why Arc is very lisp’ish including polish notation for mathematical expressions. Actually the code examples are so incredible short to do a lot of stuff I guess I will try some sort of prototyping with it in the future. The plan is to design Arc to be useful in 100 years. This means time for adoption.

Filed under , , , , , , , & six comments & no trackbacks

Fleeing the documentation hell 14

Lately I was in need of a good documentation solution. Not just plain simple API documentation but more or less a tool which helps me to author technical manuals. There are a few approaches: the traditional solution with LaTeX and a number of converters (HTML, PDF, etc.), the more modern approach is DocBook which focuses on documentation not on typography and formatting as LaTeX does. Dita looked really promising too but the state of the toolchain explains fairly well why this is no option at all. One could say that there is just no state. The last option when nothing else fits is using a random Wiki technology or a simple text formatting tool like Textile or Markdown. I wanted to avoid that as I like to have a documentation toolkit with specific documentation semantics, not just a text formatter.
Back to DocBook: DocBook is first of all a huge grammar which scared me. The good thing is however, that most of the time you just need a rudimentary subset of it.
Until version 5.0 only DTDs were officially supported. I had have a hard time struggeling with DTDs in the past so I really wanted to avoid such trouble again. Additionally DTDs are painful to extend so having basic functionality like the XInclude extension is no fun.
Using 5.0 is also really brave from a toolchain perspective: xmllint from libxml2 insists on having a DTD even though modern format description grammars like Relax NG or XML Schema do not require them. I really like xmllint for – nobody would have guessed that – linting XML trees and resolving XML includes but it striked when not having a DTD. Finally the Sun MSV looked promising enough and worked out well, except that it is not willing to return with an exit code > 0 on failure. Also MSV is not capable of xincludes so I’m now having a three-step conversion of my DocBook 5 files: first of all sticking together the files via xincludes with xmllint (no validation, so no errors occur). Than validating the DocBook against a Relax NG scheme which is capable of Xincludes and finally running an XSLT transformation with good old xsltproc. PHPs DOMDocument theoretically provides relaxNGValidate() which could solve the problem as well but sadly there is no row/column information provided where the validation actually failed. Just knowing there is an error but not knowing where is somewhat useless for a validation tool.
After having solved the toolchain problem with the Sun Java Tool DocBook 5.0 was the way to go. No DTDs, specific semantics for technical documentation, even specific semantics for object documentation (like the ooclass- and ooexception-element).
While digging into DocBook 5.0 I found out that this version makes DocBook itself more XMLish, which is nice. A number of XML standards are now supported as is: the old “id” attribute for naming element references is now an xml:id-attribute from the XLink, there are default schemas for XInclude and MathML is incorporated. So far I’m happy with that.

Filed under , , , , & 14 comments & no trackbacks

Self-ish 7

Did you know that this is working?

<?php
class MyClass
{
   public function doSomething(self $obj)
   {}
}

self is a valid typehint for MyClass.

Filed under , & seven comments & no trackbacks

Quality assurance with __call(), __get(), __set() 0

__call(), __get() and __set() are so called magic functions of PHP-classes. __set() is called, when you’re trying to overload a property of a class, __get() is called, when you trying to fetch a property which is undefined and __call is executed if you’re going to call a method which is not defined. Example:

class Test
{ public function __set( $name, $value ) { echo “Name: {$name}\n”; echo “Value: {$value}\n”; }

public function __get( $name ) { echo “Name: $name\n”; } public function __call( $method, $parameter ) { echo “Method {$method} called with following parameter:\n”; var_dump( $paramter ); } }
This should be enough, to understand what this functions are doing. Now you can modify the magic functions to log its error messages or to trigger a warning. One hint: Also it seems, it’s not a good idea to throw an exception, because this will lead to silent stops in your program in combination with register_callback_function(). A good idea is to create a base-class, which provides such QA-mechanisms for free and all of your classes are children of this class. Also it would be a good idea if something like this would be implemented in PHP.

Filed under , , , , , & no comments & no trackbacks

Symbole in PHP emulieren 0

PHP bietet von Haus aus keine Symbole. Ist es in Sprachen wie Ruby möglich, Symbole als Methoden-Argumente zu verwenden, so entfällt diese Möglichkeit in PHP. Dabei bieten Symbole im Gegensatz zu Werten oftmals große Vorteile: sie ermöglichen API-Stabilität, auch wenn sich die Funktionalität einer Klasse beständig ändert, denn das Zuweisen eines Wertes kann in der Klasse bzw. Methode geschehen. Auch wenn sie PHP nicht mitbringt, gibt es eine Möglichkeit, solche Symbole zu emulieren.
Erst einmal ein Beispiel in Ruby:

class Bla
        def self.foobar( param )
                print “Here we are!\n” if param == :sym
        end
end

bla = Bla;
bla.foobar( :sym )

Nun bietet PHP seit der Version 5.0 bekanntermaßen ja Klassen-Konstanten, die sich für diesen Zweck recht praktisch missbrauchen lassen. Das bekannte Beispiel in PHP:

class Bla
{ const SYM = “bla”; public function foobar( $param ) { if( $param == Bla::SYM ) print “Here we are!\n”; }
}

$bla = new Bla;
$bla->foobar( Bla::SYM );


Nachteile hat das Verfahren kaum, nur dass die Parameterliste oftmals sehr lang wird, wenn mehrere Klassen-Konstanten als Argumente übergeben werden und sprechende Klassen- bzw. Parameternamen verwendet werden.

Filed under , , , , , , , & no comments & no trackbacks