Tip: Symfony2 Production Settings With Doctrine Checks

I found today a tip from the doctrine configuration and command to check for production settings correctness.

The command in question is the following:

~ php app/console doctrine:ensure-production-settings --env=prod
Proxy Classes are always regenerating.

As you can see even in production server it would want to fail because of the autoregenerate of proxy classes set by the debug flag. Because you want to also not wait until production by try production in your local you want to force this flag to allow to mimic the real slim shady nature of your production server.

To do this run:

~ php app/console doctrine:ensure-production-settings --no-debug --env=prod
PHP Fatal error:  Class 'FOS\UserBundle\Entity\UserListener' not found in /home/cordoval/sites-2/app/cache/prod/appProdProjectContainer.php on line 340
PHP Stack trace: ...

Woah! Not coolio, so obviously the problem is you have forgotten to clear the cache on production. After doing this cache:clear –env=prod then you will be greeted after doing all well with:

~ php app/console doctrine:ensure-production-settings --no-debug --env=prod
Environment is correctly configured for production.

I personally would not bet my heart on these checkers, since if you are using multiple connections for instance I sincerely doubt it checks the settings for each one of them all. However this is a good start to create checks for your production environment, thing largely unexplored in the open source field since everybody assumes you are an expert deploying on production like a boss. My advise is to create checks yourself and maybe open source these checks and share them. Of course the productions settings ensuring command boils down to just 3 checks and for this …

Feel free to override the ORM\Configuration class method if you add more checks or create another similar command that invokes also this logic like “grace:check-system-settings-for-security-and-production“:

  /**
     * Ensures that this Configuration instance contains settings that are
     * suitable for a production environment.
     *
     * @throws ORMException If a configuration setting has a value that is not
     *                      suitable for a production environment.
     */
    public function ensureProductionSettings()
    {
        if ( ! $this->getQueryCacheImpl()) {
            throw ORMException::queryCacheNotConfigured();
        }
 
        if ( ! $this->getMetadataCacheImpl()) {
            throw ORMException::metadataCacheNotConfigured();
        }
 
        if ($this->getAutoGenerateProxyClasses()) {
            throw ORMException::proxyClassesAlwaysRegenerating();
        }
    }

You see here that doctrine only checks its back, naturally just cache configuration, metadata cache, and regeneration of proxy classes. You could add for instance reverse settings, and what not. Share your ideas on the comments below.

I am so thankful I am running in some neat things I have missed for not reading enough. Now by God’s undeserved grace I will do my best to try to blog post and continue the phpspec series.

Encouragements and keep the support up please if you can send me to Warsaw to learn more and share 🙂

Your friend cordoval.

How to be a good Apprentice: PHPSpec Pimple Part II

So today I solved a couple of problems and got this running much better yet still incomplete. However notice the new details, it feels like one is learning the way things should be done with the tool more and more and return from the hacky way to the phpspec way.

<?php
 
namespace spec;
 
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use ReflectionFunction;
 
class PimpleSpec extends ObjectBehavior
{
    function it_is_initializable_and_implements_array_access()
    {
        $this->shouldHaveType('Pimple');
        $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->trueOffsetGet('service')->shouldHaveType('SplObjectStorage');
    }
 
    function it_nests_an_offsetGet_method_to_avoid_collisions_with_PHPSpec()
    {
        $this['service'] = function() { return new \SplObjectStorage(); };
 
        $this->offsetGet('service')->shouldBeLike($this->trueOffsetGet('service'));
    }
 
    function it_executes_with_container_argument_when_value_is_a_factory()
    {
        $this['container'] = function($container) { return $container; };
 
        $this->executeFactory('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');
    }
 
    public function getMatchers()
    {
        return [
            'beAClosure' => function($subject, $closure) {
                $rf = new ReflectionFunction($closure);
                $result = call_user_func($closure) === call_user_func($subject);
                return $rf->isClosure() && $result;
            },
            'returnWhenInvokedWith' => function($subject, array $resultAndArgument) {
                return $resultAndArgument[0] === call_user_func($subject, $resultAndArgument[1]);
            }
        ];
    }
}

Some things to notice is I needed less custom matchers than at the beginning. I am leaving them here just for reference and to grow a library.

Also to be noticed is the fact that I use a wrapper method for the offsetGet because ObjectBehavior object is an ArrayAccess as well.

<?php
 
class Pimple implements ArrayAccess
{
    protected $collection = [];
 
    public function offsetSet($offset, $value)
    {
        $this->collection[$offset] = $value;
    }
 
    public function offsetUnset($offset)
    {
 
    }
 
    public function offsetExists($offset)
    {
        return array_key_exists($offset, $this->collection);
    }
 
    public function offsetGet($offset)
    {
        return $this->trueOffsetGet($offset);
    }
 
    public function trueOffsetGet($offset)
    {
        if (is_object($this->collection[$offset]) && method_exists($this->collection[$offset], '__invoke')) {
            return $this->executeFactory($offset);
        }
 
        return $this->collection[$offset];
    }
 
    public function executeFactory($offset)
    {
        return $this->collection[$offset]($this);
    }
}

Encouragements in all good!

School of Prophets: Start Small, start with Pimple

Lately I decided to speck Pimple :). PHPSpec is a great tool, but everytime that I look more into it and the people who use it I am more convinced that it is like a school. First of all you learn BDD Specking type by doing, by a change of mindset, someone external apply it to you or you happen to mock it at least to be ready, or a combination. Yeah some abc of theology mixed into the explanation.

A good `prophet` knows how to describe objects in a way that the behavior is clean and directed, he has to convey the message and not babbling. He studies and reacts to what he sees and keeps conveying compulsorily the message/specification that the divine person behind him/her has revealed. The greater design of the divine person is also revealed to even the prophet himself/herself, some people called this emergent design, which I think is a discovery of what is there but is unseen up to the point of specking.

So I start looking at the PHPUnit tests of Pimple to do a regression. It is also good that even though I have looked at Pimple before I have never understood why some decisions were taken.

So my first describing of things was that the class was of the Pimple type:

    function it_is_initializable()
    {
        $this->shouldHaveType('Pimple');
    }

Then the next test on the suite was that Pimple can store strings:

    function it_stores_strings()
    {
        $this['param'] = 'value';
        $this['param']->shouldReturn('value');
    }

It was until I went to the this test that PHPSpec told me I had to implement ArrayAccess itself. I then wrote:

    function it_is_initializable()
    {
        $this->shouldHaveType('Pimple');
        $this->shouldImplement('ArrayAccess');
    }

That nailed it. Then the next test was:

    function it_stores_closures()
    {
        $this['callback'] = function() { return 5; };
 
        $this['callback']->shouldBeAClosure(function() {return 5;});
    }

Yep, you can also store closures. All tests were green up to this point. I had to discover and do a custom matcher for the above thing to work:

public function getMatchers()
    {
        return [
            'beAClosure' => function($subject, $closure) {
                $rf = new ReflectionFunction($closure);
                $result = call_user_func($closure) === call_user_func($subject);
                return $rf->isClosure() && $result;
            }
        ];
    }

This basically hacky way ensures it is the closure that gets in that gets out.

Then I ran into Pimple’s probably most neat feature looking forward to automating Dependency Injection in an ArrayAccess object.

    function it_passes_itself_when_stored_value_called_takes_an_argument()
    {
        $this['container'] = function($container) { return $container; };
 
        $this['container']->shouldReturnWhenInvokedWith(array($this, $this));
    }

And I had to add the matcher:

            'returnWhenInvokedWith' => function($subject, array $resultAndArgument) {
                return $resultAndArgument[0] === call_user_func($subject, $resultAndArgument[1]);
            }

All was green and great until I realize I had not written any code on Pimple, yet I knew something was wrong because this should be a feature.

I understood that Pimple’s behavior when an object closure is injected/stored when invoked it has to take Pimple as an argument. That logic was not happening.

And for tonight it is here where it ends, because I have to ask the more learned guys, even the creator @everzet, and @md, or @jakzalas to see how to approach this scenario.

Notice the next tests are easy and hard. So it would be interesting how to resolve this problem.

Until next time, I enjoyed tonight. Lord willing there will be more PHPSpec in Warsaw SymfonyCon.

Thankful for my Saviour’s totally undeserved favor and grace.

Selection_556

He he sorry, only valid part of the graphic ends before Scripture\Memory. 🙂 I wrote it on top of another project I was thinking about.

Challenge Made Public Using Symfony2 Bleeding Tweaks

It is well known I attended desymfony conference in Madrid, Spain.

There a company handed out some leaflets and threw up a challenge.

I want to share the challenge with you the symfony way in my attempt even with help from some good friends but incomplete:

https://github.com/cordoval/dragon

Nevertheless, trying and willing is passion!

Encouragements in all good!

<?php
 
namespace Dragon;
 
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
 
/**
 * A dragon flies in a series of one-fifth circular arcs (72).
 * and with a free choice of a clockwise or an anticlockwise arch
 * for each step.
 *
 * - any arch may be traversed multiple times
 * - in each step, the direction change must be exactly +/- 72
 * - both the starting and the end direction must be north
 * - all arcs must have the same radius
 */
class PathEngineCommand extends Command
{
    const length = 5;
    const nodes = 5;
 
    public $d;
 
    protected function configure()
    {
        $this
            ->setName('path_engine_command')
        ;
    }
 
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->initDMatrix($this->d);
 
        $output->writeln($this->f(0, self::length, $output));
    }
 
    public function initDMatrix()
    {
        foreach(range(0, self::nodes - 1) as $i) {
            $this->d[$i] = array_fill(0, self::length + 1, -1);
        }
    }
 
    public function f($x, $y, OutputInterface $output)
    {
        if ($y < 0) {
            return 0;
        }
 
        if ($y == 0){
            if ($x == 0) {
                return 1;
            }
 
            return 0;
        }
 
        if ($this->d[$x][$y] != -1) {
            return $this->d[$x][$y];
        }
 
        $this->d[$x][$y] = 0;
        $this->d[$x][$y] = $this->f(($x + 1) % self::nodes, $y - 1, $output) + $this->f(($x - 1 + self::nodes) % self::nodes, $y - 1, $output);
 
        $table = $this->getApplication()->getHelperSet()->get('table');
        $table->setRows($this->d);
        $table->render($output);
 
        return $this->d[$x][$y];
    }
}

I miss the trigonometric part that substracts the paths that end up in the same direction but that do not close back to the origin.

Quick Web Console for Rapid PHP Prototyping

Today I ran into a pearl by skimming over @Seldaek’s repos. I found this https://github.com/Seldaek/php-console.
It is a web type console, like those online consoles where we can try our snippets, the thing is this console is private and local so it is safer and more open source :).

I thought about this console and did followed the instructions and ran:

composer create-project --stability=dev --keep-vcs seld/php-console

This created a folder with the repo inside. The worries came when I had to set it up and do the vhost and what not. So I decided to just have a makefile file like in @igorw’s repos and tell it to run right after the composer command, so immediately. This would allow that in the future we can just run the console anytime by typing just “make“ or even just “composer install –dev“ since this will also run the former.

Selection_554

And when opening the browser this works, however a bit ugly, i think there is some problem with the templates and old php code.
Nothing that a good PR cannot solve 🙂

Selection_555

Enjoy, encouragements in all good!