PHP FREAKSHOW
LEONARDO TUMADJIAN
THE DEVELOPERS CONFERENCE - SÃO PAULO
25/07/2015
SOBRE MIM:
Formado em Análise e Desenvolvimento de Sistema pela Estácio UniRadial
Programador PHP desde 2009
Instrutor desde 2012
Nas horas vagas: Gamer, Biker, Shooter
Evangelista da comunidade PHPSP
Víciado em séries estranhas!
RECOMENDO ASSISTIR =D
ANTES DE COMEÇARMOS:
Contribua com sua comunidade mais próxima, se tiver um tempo ;)
Como contribuir?
ATENÇÃO!
O conteúdo a seguir pode conter cenas fortes, códigos sujos, violência contra as boas práticas, esquisitices, loucuras e muito mais..
Em caso de fortes problemas cardíacos prefira: Design Patterns, SOLID, DDD e etc..
Não tente fazer isso em casa, e muito menos no trabalho, obrigado!
WELLCOME!
Sejam bem vindos ao PHP Freak Show, o show já vai começar, preparem-se.
AINDA DA TEMPO DE CORRER
NÃO?
OK, ENTÃO...
VARIÁVEIS VARIÁVEIS!
A mulher elástica
$first = 'what';
$what = 'the';
$the = 'hell';
$hell = 'is this!?';
echo $$$$first; // Imprime: is this!?
// ...
private $mine='No!!';
public function getProp($prop)
{
    return $this­>$prop;
}
// ...
$robot = new Robot('Mike', 436878);
$mine = $robot­>getProp('mine');
var_dump($mine);
// Imprime: string 'No!!' (length=4)
AGORA A ABERRAÇÃO:
Preparados?
// ...
$obj = 'myRobot';
$class = 'Robot';
$param1 = 'Robotron';
$param2 = 5532;       
$method = 'say';
$word = 'Hello Humans';
$$obj = (new $class($param1, $param2))­>$method($word); // Imprime Hello Humans
// ...
STANDARD PHP LIBRARY
O gigante de quatro braços
USAREMOS:
1. ArrayIterator
2. ArrayAccess(Interface)
PRIMEIRA LOUCURA
class Writer extends ArrayIterator
{
    public function offsetGet($index) 
    {
        echo $index . ' ';
        return $this;
    }
}
$whiter = new Writer();
$whiter['Hello']['World']; // Imprime: Hello World
$whiter['But']['when']['this']['is']['over?']; // Imprime: But when this is over?
CALMA!
SEMPRE PODE PIORAR!
POSSO?
class Crazy implements ArrayAccess 
{
    // ... some code here
    public function offsetGet($offset) 
    {
        $this­>phrase[] = $this­>tagIn() . $offset . $this­>tagOut();
        return $this;
    }
    // ...
    public function color($colorHex)
    {
        $last = &$this­>phrase[count($this­>phrase)­1];
        $last = '<div style="color: ' . $colorHex .'">'
                . $last . '</div>';
        return $this;
    }
    // ... more code bellow
}
AGORA VAMOS USA-LA?
// Using the class Crazy!
$crazy = new Crazy;
$crazy['Hello']
        ['world']
        ['what`s up?']
        ['is this']
        ['too']
        ['crazy for you?']
        ­>write();
E agora? Onde está seu deus?
// Using the class Crazy!
$crazy = new Crazy;
$crazy['Hello']
        ['world']­>color('blue')
        ['what`s up?']
        ['is this']­>color('red')
        ['too']
        ['crazy for you?']­>color('green')
        ­>write();
RESULTADO DO ÚLTIMO CÓDIGO:
VARIADICS
PHP 5.6+ O Lobsomen!
class Robot
{
    public function talk($parm1, $parm2)    
    {
        echo $parm1, $parm2;
    }
}
$arr = ['hello', 'world'];
// Old but GOLD
call_user_func_array([new Robot, 'talk'], $arr);
// OR WARNING PHP 5.6+
$robot = new Robot;
$robot­>talk(...$arr);
INSTANCIANDO OBJETOS E ARRAY
DEREFERENCING
O Camaleão
class Robot
{
    // ...
    public function getBag()    
    {
        return ['arms','legs','shoulders','head'];
    }
    // ...
    public function sayHello()
    {
        echo 'Hello Human';
    }
}
UTILIZANDO A CLASSE:
// Gangsta style execute sayHello
(new Robot)­>sayHello(); // Imprime: Hello Human
// Array Dereferencing
echo (new Robot)­>getBag()[1]; // Imprime: legs
MÉTODOS MÁGICOS
O mago
Aos Javeiros!
MÉTODOS DISPONÍVEIS
__construct __destruct __get __set __isset __unset __sleep __wakeup __clone
__invoke __call __callStatic __set_state __debugInfo
class DataMaker
{
    protected $matrix;
    // ...
    public function __call($name, $args) 
    {
        $this­>matrix[$name] = $args[0];
        return $this;
    }
    // ...
}
$dados = (new DataMaker)
        ­>nome('Leonardo')
        ­>telefone('11 95555­2233')
        ­>endereco('Rua Teste 123')
        ­>teste('colocando char especial')
        ­>toClass('Customer');
        
var_dump($dados);
RETORNO:
object(Customer)[2]
  public 'nome' => string 'Leonardo' (length=8)
  public 'telefone' => string '11 97379­7752' (length=13)
  public 'endereco' => string 'Rua Teste 123' (length=13)
  public 'teste' => string 'colocando char especial' (length=23)
ALGUMAS IDEIAS USANDO UM ROUTER:
// A crazy Router interface
(new GET)['/ola']
        ­>controller('Carro')
        ­>action('hello');
        
// A Fluid Interface Programming
request('POST')
    ­>to('/cliente')
    ­>controller('Carro')
    ­>action('hello');
// Pratical Router
$post = new Post;
$post['/hello'] = function ($name) {
    return 'Hello ' . $name;
};
UM POUCO DE CÓDIGO ÚTIL
// Strange Data Mapper
// Update data
(new Funcionario)[2]
        ­>nome('Leonardo')
        ­>endereco('Rua 123, teste 12')
        ­>email('novoemail@teste.com');
// Get data from Database
$funcionario = (new Funcionario)[2];
echo $funcionario­>nome; // Imprime nome do funcionario id 2
BOM ACHO QUE ACABAMOS..
// A crazy Closure Class
// ...
(new CrazyClosure(function($a, $b, $c){
    echo 'In:', $a, $b, $c;
}, function($a, $b, $c) {
    echo 'Out:', $a, $b, $c;
}))[Closure::bind(function () {
    return [1,2,3];
}, new stdClass)­>__invoke()]; // Imprime In:123Out:123
// O.O
Hey! espera! não, não faça isso!
CENAS DOS PRÓXIMOS CAPÍTULOS..
PHP 7.0.0Beta2
// PHP 7.0.0Beta2
echo (new class extends ArrayIterator {
    public $name;
    public function offsetGet($name)
    {
        $this­>name = $name;
        return $this;
    }
    public function hello(string $string) : string 
    {
        return $string . ' ' . $this­>name;
    }
})['World']­>hello('Hello');
// Imprime: Hello World
ESPERO QUE TENHAM GOSTADO, DÚVIDAS?
“Because the people who are crazy enough to think they can
change the world, are the ones who do.” ―Apple Inc.
OBRIGADO!
HTTPS://JOIND.IN/14849
SLIDES E EXEMPLOS EM:
HTTPS://GITHUB.COM/LEOQBC/PHP-FREAKSHOW

Php Freak Show por Leonardo Tumadjian