Reviewing Symfony2 The Symfony Way

The past weeks i have had a chance to review the book that is coming up in few days. It has been a privilege being able to study and review and suggest corrections to the material. I am definitely going to recommend this book to all my friends.

Selection_558

Matthias has done a superb job from first page to the end of the book. I am posting this blog to help build momentum to the community as it is precisely this type of efforts the ones that build more and more practices culture in the community.

Encouragements in all good and feel free to retweet! You will find pearls in this book!

In difficulty understanding God’s joy in doing what I do

I got an acute bronchitis over the past weeks, and my daughter just threw up because of an already treated respiratory infection. I want to say thanks God firstly, lest you think I am angry for this. I am concerned but not angry at all. I entered almost in panic because this could be A1HN1 on me or my daughter or on both or even on my entire family. If you are following the news, you will see Peru has even in this month, so weeks, cases of A1HN1 deaths in the same state I travelled to, in the capital where I live and so much more.

I cannot take it away from me, I have to go through the process and hope it is not A1HN1. Anything could happen, I am under rest for 3 days and taking injections and pills for treating the bronchitis. I have gone back to stable now and catching up with things I need to do but in the way I find myself confronted first amidst some personal family problems and also problems at fulfillment. We all want, naturally and carnally, our personal problems solved and to be someone in this life. We like the shower of what others speak about us and such. All those the result of a broken communication. It broke long time ago, not with a woman or anyone else, but with God telling us who, what, why, we are for and to ultimately express his max love in His own person, aka Christ Jesus.

I am not writing this blog post out of myself, I am sinful and have sinned in many ways even this week, today and last few seconds. I am writing this to let you see my source of strength, not how newbie, stupid, or in rare occasions how clever can someone be, but what is the central thing I consider in my life. It revolves about that communication that was broken long ago and by lack of which we don’t understand why. Why disease, why death, why jobless, why not the best, why I don’t have it together myself or with any human invention ever invented or to be invented.

This communication is restored upon believing the word of God as expressed in the Bible. Yeah you called it written by men and invented and corrupted. Yet not with reason by out of anger and lack of real careful research. It is however the only communication restoration story that could bring and fill all those vacuums. Neglecting it means death, lack of a divine question and response conversation and without meaning.

So why I code, first I got here because I tried to do an app Memorize-Scripture 2 some years ago. I left the trace. Yet I see that I am always revolving and always trying to go back to it, to Scripture. That is what drives me. Across well paid jobs seasons and across jobless seasons. Across times of apparently disfavor, and times of favor. All makes sense, because I still enjoy it thinking of the work, forgiveness and glory that awaits us with whom is capable of defeating death and do more than what we can ever imagine.

So everytime you see me blogging, I pray may you make me more glad if you have this joy in mind.

Some people have asked I continue the phpspec and stackphp series and it is in what i am thinking. I however have some small committment on a friend’s job and also the conference in Argentina on October. And also some other small PRs and a book review! I truly hope I can make it pass this flu, then I will have perhaps more energy to work on these things.
So expect more coming soon 🙂

Encouragements amidst of adversity, in Him graciously.

My friends and so much favor from God

I am so glad to share the good news I got a talk accepted for October to the phpconference.com.ar conference. One of the biggest if not the biggest in South America on PHP and more.

Selection_557

I feel very humbled and honored that totally undeserved I can have my face next to these giants of the community. I mean I respect these people for their passion and technical level on the community. It really strikes me that yeah they are also human, but they are the ones in whose shoulders we build our applications on. I also value these persons as my close friends and I am always eager to share my findings and be mentored by any of them. Thank you so much guys and thank you conference organizers.

It is all favor, favor for having the time to research and learn things, favor through helping hands on my way, and all loving favor from my Lord Jesus Christ.

Not everybody think the same as me, but they are my friends, I was put in this community and I enjoy every day I can be part of to contribute disagree, agree, and together find ways and share the favor I received.

There are more friends that are not speakers and for them I also give thanks. I often think of you guys.

PHPSpecking From Bus Tour to Huaraz: Part IV

I a on a bus PHPSpecking, today I was contributing to namshi/notificator repository and attempted to replace a phpunit test to learn Prophecy library tied to PHPSpec. Here I will show first the result and then the PHPUnit old file so you can compare. I learned lots on the way.

<?php
 
namespace spec\Namshi\Notificator;
 
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
 
class ManagerSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Namshi\Notificator\Manager');
    }
 
    function it_comes_with_no_handlers_by_default()
    {
        $this->getHandlers()->shouldHaveCount(0);
    }
 
    /**
     * @param Namshi\Notificator\Notification\Handler\HandlerInterface $handler
     */
    function it_can_hold_several_handlers($handler)
    {
        $this->addHandler($handler);
        $this->addHandler($handler);
        $this->getHandlers()->shouldHaveCount(2);
    }
 
    /**
     * @param \Namshi\Notificator\Notification\Handler\HandlerInterface $handler
     * @param \Namshi\Notificator\NotificationInterface $notification
     */
    function it_can_stop_propagation_of_notifications($handler, $notification)
    {
        foreach (range(1,6) as $i) { $this->addHandler($handler); };
        $this->getHandlers()->shouldHaveCount(6);
 
        $handler->shouldHandle(Argument::any())->shouldBeCalled()->willReturn(true);
        $handler->handle(Argument::any())->shouldBeCalledTimes(1)->willReturn(false);
 
        $this->trigger($notification);
    }
}

And here is the old class:

<?php
 
namespace Namshi\Notificator\Test;
 
use PHPUnit_Framework_TestCase;
use Namshi\Notificator\Manager;
use Namshi\Notificator\Notification\Handler\HandlerInterface;
use Namshi\Notificator\NotificationInterface;
 
 
class ManagerTest extends PHPUnit_Framework_TestCase
{
    public function setup()
    {
        $this->manager = new Manager();
    }
 
    public function testTheManagerDoesntHaveHandlersByDefault()
    {
        $this->assertCount(0, $this->manager->getHandlers());
    }
 
    public function testTheManagerCanHaveMultipleHandlers()
    {
        $this->manager->addHandler(new StubHandler());
        $this->manager->addHandler(new StubHandler());
 
        $this->assertCount(2, $this->manager->getHandlers());
    }
 
    public function testTheManagerCanTriggerNotificationsToAllHandlers()
    {
        $this->manager->addHandler(new StubHandler());
        $this->manager->addHandler(new StubHandler());
        $notification = new StubNotification();
        $this->manager->trigger($notification);
 
        $this->assertEquals(2, $notification->count);
    }
 
    public function testTheManagerCanStopPropagationOfNotifications()
    {
        $this->manager->addHandler(new StubHandler(true));
        $this->manager->addHandler(new StubHandler());
        $this->manager->addHandler(new StubHandler());
        $this->manager->addHandler(new StubHandler());
        $this->manager->addHandler(new StubHandler());
        $this->manager->addHandler(new StubHandler());
        $notification = new StubNotification();
        $this->manager->trigger($notification);
 
        $this->assertCount(6, $this->manager->getHandlers());
        $this->assertEquals(1, $notification->count);
    }
}
 
class StubHandler implements HandlerInterface
{
    public function __construct($stopPropagation = false)
    {
        $this->stopPropagation = $stopPropagation;
    }
 
    public function shouldHandle(NotificationInterface $notification)
    {
        return true;
    }
 
    public function handle(NotificationInterface $notification)
    {
        $notification->count++;
 
        if ($this->stopPropagation) {
            return false;
        }
    }
}
 
class StubNotification implements NotificationInterface
{
    public $count = 0;
 
    public function getParameters()
    {
 
    }
 
    public function setParameters(array $parameters)
    {
 
    }
}

Things to notice:

– We don’t have to do a mental effort on writing the method names for testing and just write describing true features of our object
– You want to save your mental energy to describe behavior not to read difficult camel case names on tests. I mean we are cool with camel case on the class but not need for them when describing specific features of the behavior.
– Looking underneath those `should`s, `will`s and `shouldHave`s is the core mind of what Prophecy is. It is similar to reality where it has to do with hope, fulfillment, and scrutinizing fulfillment to convey one step at a time a widening panorama of the salvation plan and the divine person self revealing. In our case is design, we prophesy by describing using these tools and the design force implements these expectations that get fulfilled in its time. The descriptions remain to validate the body of truth about the design. These methods are really just built-in shortcuts to mock and stub and to set forth for us object manipulations with which we can take onto this task.
– If you compare both codes, you will see that the shortcuts make PHPSpec superior and cleaner, more easy to read than its predecessors.
– One really neat thing that PHPSpec would prompt you to, is the fact that it will fire up a special exception if part of the behavior of your class gets called but it is not specified or described. This thing is really useful because it keeps you accountable and true with the context of how your collaborators are used in the story you are telling.
– As a result you will also observe that we need nothing extra besides our testing class. We don’t need to pollute the file we are in with adhoc classes created just for stubbing or mocking. PHPSpec plays hand in hand with Prophecy to help you do this without being too verbose. You will focus on behavior not on boiler plat code with this tool.
– The other thing not to miss is the concept of arguments. When you are specking with PHPSpec arguments are not plain arguments but objects that will help you intelligently address internal needs and expectations. This has to do with addressing specific behavior for calls of the methods described with specific signatures and arguments. Prophecy has a built-in voting mechanism in which your matching has scores and the best signature fit case will win. Smart move from @everzet and @_md.
– Again from 92 lines to 44 lines. I am not sure about you but I see a winner.

Man i am seing beautiful mountains here. I will try to post some images on a later blog post. Going in zigzag right now through the valleys high altitudes and amazing places of Peru in a bus that powers this asus g73 gaming grade 🙂 (retina is on repair).The only thing that is making me sick is the smell or artificial cleaning smell on the bus. That combined with the roller coaster in the few hours hopefully will not be enough to make me throw up. I hope you guys enjoy learning with me so far. I am very thankful for all this undeserved specking tour.

PHPSpec Home Schooling: Part III – Let’s do it guys /o/

Ok, so here is what i came up with a bit of more work. It is just the tests, I think there were some basic improvements but also I notice some things could be done to shorten or simplify the size of the original phpunit test file.

<?php
 
namespace spec;
 
use PhpSpec\ObjectBehavior;
 
class PimpleSpec extends ObjectBehavior
{
    function it_is_initializable_and_implements_array_access()
    {
        $this->shouldImplement('ArrayAccess');
    }
 
    function it_stores_strings()
    {
        $this['param'] = 'value';
 
        $this['param']->shouldReturn('value');
    }
 
    function it_stores_executable_closures()
    {
        $this['service'] = function() { return new \SplObjectStorage(); };
 
        $this->offsetGet('service')->shouldHaveType('SplObjectStorage');
    }
 
    function it_returns_different_instances_from_factories()
    {
        $this['service'] = function() { return new \SplObjectStorage(); };
 
        $this->offsetGet('service')->shouldBeLike(new \SplObjectStorage());
        $this->offsetGet('service')->shouldNotBe(new \SplObjectStorage());
    }
 
    function it_executes_with_container_argument_when_value_is_a_factory()
    {
        $this['container'] = function($container) { return $container; };
 
        $this->offsetGet('container')->shouldReturn($this);
    }
 
    public function it_responds_to_isset()
    {
        $this['param'] = 'value';
        $this['service'] = function () { return new \SplObjectStorage(); };
        $this['null'] = null;
 
        $this->shouldHaveKey('param');
        $this->shouldHaveKey('service');
        $this->shouldHaveKey('null');
        $this->shouldNotHaveKey('non_existent');
    }
 
    function it_takes_key_value_pairs_via_constructor()
    {
        $this->beConstructedWith(['param' => 'value']);
        $this->offsetGet('param')->shouldReturn('value');
    }
 
    function it_tests_key_is_present()
    {
        $exception = new \InvalidArgumentException('Identifier "foo" is not defined.');
        $this->shouldThrow($exception)->duringOffsetGet('foo');
    }
 
    function it_holds_and_honors_null_values()
    {
        $this['foo'] = null;
        $this['foo']->shouldReturn(null);
    }
 
    function it_supports_unset()
    {
        $this['param'] = 'value';
        $this['service'] = function() { new \SplObjectStorage(); };
 
        unset($this['param'], $this['service']);
        $this->shouldNotHaveKey('param');
        $this->shouldNotHaveKey('service');
    }
 
    function it_shares_a_persistent_common_instance()
    {
        $this['shared_service'] = $this->share(function() { return new \SplObjectStorage(); });
        $service = $this->offsetGet('shared_service');
        $this->offsetGet('shared_service')->shouldNotBe(null);
        $this->offsetGet('shared_service')->shouldBe($service);
    }
 
    function it_can_fence_callback_from_being_factored()
    {
        $callback = function() { return 'foo'; };
 
        $this['protected'] = $this->protect($callback);
        $this->offsetGet('protected')->shouldBe($callback);
    }
 
    function it_fences_function_names_treating_them_as_parameters()
    {
        $this['global_function'] = 'strlen';
        $this->offsetGet('global_function')->shouldBe('strlen');
    }
 
    function it_gives_back_raw_value()
    {
        $this['service'] = $definition = function() { return 'foo'; };
        $this->raw('service')->shouldBe($definition);
    }
 
    function it_gives_back_raw_nulls()
    {
        $this['foo'] = null;
        $this->raw('foo')->shouldBe(null);
    }
 
    function it_tests_key_present_on_raw_call()
    {
        $exception = new \InvalidArgumentException('Identifier "foo" is not defined.');
        $this->shouldThrow($exception)->duringRaw('foo');
    }
 
    function it_can_extend_values()
    {
        $this['shared_service'] = $this->share(function() { return new \SplObjectStorage(); });
        $value = 123;
        $assignmentDecorator = function($sharedService) use ($value) {
            $sharedService->value = $value;
 
            return $sharedService;
        };
        $this->extend('shared_service', $assignmentDecorator);
 
        $this->offsetGet('shared_service')->shouldHaveType(get_class($this->offsetGet('shared_service')));
        $this->offsetGet('shared_service')->value->shouldBe($value);
        $this->offsetGet('shared_service')->value->shouldBe($this->offsetGet('shared_service')->value);
        $this->offsetGet('shared_service')->shouldBe($this->offsetGet('shared_service'));
    }
 
    function it_can_list_all_keys_present()
    {
        $this['foo'] = 5;
        $this['bar'] = 7;
        $this->keys()->shouldReturn(['foo', 'bar']);
    }
 
    function it_checks_for_valid_key_when_extending()
    {
        $exception = new \InvalidArgumentException('Identifier "foo" is not defined.');
        $this->shouldThrow($exception)->duringExtend('foo', function() {});
    }
 
    function it_invokes_factory_when_value_is_an_invokable_object()
    {
        $this['invokable'] = new Invokable();
        $this->offsetGet('invokable')->shouldReturn('I was invoked');
    }
 
    function it_treats_non_invokable_object_as_a_parameter()
    {
        $objectParameter = new \StdClass();
        $this['non_invokable'] = $objectParameter;
        $this->offsetGet('non_invokable')->shouldReturn($objectParameter);
    }
}
 
class Invokable
{
    function __invoke()
    {
        return 'I was invoked';
    }
}

Things to notice:

– The tests involving special functional methods are the hardest to implement upon given specification.
– If we cluster all setup into a let() method this class could go downto few lines but may not be a good idea
– The final size is 174 lines compared to the 270 lines of phpunit. An extra of 270 – 174 = 96 lines!!
– The clarity of the code is amazing and the method naming is perfect and clear
– The shortening of line numbers would be even more dramatic should we need to do more mocking
– Notice Pimple is probably one of the smallest cases you would find of something very powerful and useful
– Now we can refactor without fear and experiment with Pimple and why it was build the way it was built
– Now we can understand which functionality was added with time to support the Silex framework

I don’t want to cheat more and copy the implementations of the hard methods since this involves functional thinking and better implementations could come, so I will keep working on different implementations.
This Spec can be handed out and we can start creating a PimpleInterface so that even we, yes we, can create our own di container called ‘Simple’ :), very simple right?

I even sent this PR https://github.com/fabpot/Pimple/pull/76

Very glad I am enjoying this graceful and totally undeserved learning :)! I hope you are too!

John ~ Revelation 22:
“6 The angel said to me, “These words are trustworthy and true. The Lord, the God who inspires the prophets, sent his angel to show his servants the things that must soon take place.”
7 “Look, I am coming soon! Blessed is the one who keeps the words of the prophecy written in this scroll.”
8 I, John, am the one who heard and saw these things. And when I had heard and seen them, I fell down to worship at the feet of the angel who had been showing them to me. 9 But he said to me, “Don’t do that! I am a fellow servant with you and with your fellow prophets and with all who keep the words of this scroll. Worship God!””