2. Who am I
● PHP freelancer from 2005
● Writer for php|architect, DZone
● Perito informatico, undergraduate
in Engineering at Politecnico di
Milano
3. This talk
● Maintainability, and why testing
● Various techniques to favor ease
of testing AND maintainability
● Slides in English (test d'unità,
Legge di Demetra...)
20. 2. Avoid static methods (before)
<?php
class Collection
{
public function find($key)
{
Sorter::sort($this);
// ..search stuff
}
}
21. 2. Avoid using static methods (after)
<?php
class Collection
{
public function find($key)
{
$this->_sorter->sort($this);
// ..search stuff
}
}
22. 3. Law of Demeter
● Do not walk the... arrows
● Exceptions: Factories, data
structures
23. 3. Law of Demeter (without)
<?php
class PC
{
public function powerOn()
{
$this->_mobo->cpu->cache
->powerOn();
}
}
24. 3. Law of Demeter (with)
<?php
class PC
{
public function powerOn()
{
foreach ($this->_powered as
$item) {
/** @var Powered $item */
$item->powerOn();
}
}
}
25. 3. Law of Demeter (with)
<?php
class PC
{
public function powerOn()
{
$this->_mobo->powerOn();
}
}
26. 4. Singleton vs. Factory
● Singleton is static, impossible to
mock
● Global state
● Hidden dependency
27. 4. Singleton vs. Factory
<?php
class Authenticator
{
public function login($user,
$pass)
{
Db::select(...);
}
}
28. 4. Singleton vs. Factory
<?php
class Authenticator
{
public function __construct(Db $db)
{ ... }
public function login($user, $pass)
{
$this->_db->select(...);
}
}
29. Be honest
● If you need something, inject it (or
inject its factory)
● Tell > Ask > Look
Recipe for a clear, clean Api