PHP Composer: Check the licenses of the packages you are using in your project

Software License
Software License

It’s not very often that developers know or check the licenses used by the packages in their project, Failure to adhere to a license can have serious repercussions especially when building commercial software for clients. Therefore it is a good habit to know what licenses your project requires and making sure you get the appropriate libraries which cater for that – or just paying for the license.

A client of ours (Commercial Symfony2 application) asked my team about the bundles and packages we were using in his application and what kind of licenses they came with. He was happy with the functionality but just needed to make sure if he needs to pay for any of them.

Posed with such a question, I remembered vaguely reading through the Composer documentation about a feature which allowed for checking of licenses on the project’s packages.

As it turns out, you can check the licenses of the packages used in your project with this simple command on Composer.

./composer licenses

You should get an output similar to the one below.
NB: The output is from a Symfony2 project.

Name: symfony/framework-standard-edition
Version: 2.4.x-dev
Licenses: MIT
Dependencies:

doctrine/annotations v1.1.2 MIT
doctrine/cache v1.3.0 MIT
doctrine/collections v1.2 MIT
doctrine/common v2.4.1 MIT
doctrine/data-fixtures v1.0.0 MIT
doctrine/dbal v2.4.2 MIT
doctrine/doctrine-bundle v1.2.0 MIT
doctrine/doctrine-fixtures-bundle dev-master 351bcc4 MIT
doctrine/doctrine-migrations-bundle dev-master 667f208 MIT
doctrine/inflector v1.0 MIT
doctrine/lexer v1.0 MIT
doctrine/migrations dev-master 0742fc7 LGPL
doctrine/orm v2.4.2 MIT
friendsofsymfony/jsrouting-bundle 1.5.3 MIT
gedmo/doctrine-extensions dev-master e16bc46 MIT
gregwar/captcha v1.0.10 MIT
gregwar/captcha-bundle dev-master 8199d20 MIT
incenteev/composer-parameter-handler v2.1.0 MIT
jdorn/sql-formatter v1.2.17 MIT
jms/aop-bundle 1.0.1 Apache
jms/cg 1.0.0 Apache
jms/di-extra-bundle 1.4.0 Apache
jms/metadata 1.5.0 Apache
jms/parser-lib 1.0.0 Apache2
jms/security-extra-bundle dev-master 66d9c79 Apache2
knplabs/knp-components 1.2.5 MIT
knplabs/knp-paginator-bundle dev-master 0558122 MIT
kriswallsmith/assetic v1.1.2 MIT
monolog/monolog 1.7.0 MIT
oldsound/rabbitmq-bundle v1.2.1 MIT
phpoffice/phpexcel dev-master 0322690 LGPL
phpoption/phpoption 1.4.0 Apache2
psr/log 1.0.0 MIT
ptachoire/cssembed v1.0.2 MIT
raulfraile/ladybug v1.0.8 MIT
raulfraile/ladybug-bundle v1.0.0 MIT
raulfraile/ladybug-installer v1.0.1 MIT
raulfraile/ladybug-plugin-extra v1.0.1 MIT
raulfraile/ladybug-plugin-symfony2 dev-master 81a50bd MIT
raulfraile/ladybug-theme-modern v1.0.6 MIT
sabre/vobject 3.1.3 BSD-3-Clause
sensio/distribution-bundle v2.3.4 MIT
sensio/framework-extra-bundle v3.0.0 MIT
sensio/generator-bundle v2.3.4 MIT
stfalcon/tinymce-bundle dev-master 435bced MIT
stof/doctrine-extensions-bundle dev-master ec56540 MIT
swiftmailer/swiftmailer v5.0.3 MIT
symfony/assetic-bundle v2.3.0 MIT
symfony/icu v1.2.0 MIT
symfony/monolog-bundle v2.5.1 MIT
symfony/swiftmailer-bundle v2.3.5 MIT
symfony/symfony v2.4.2 MIT
tecnick.com/tcpdf 6.0.061 LGPLv3
twig/extensions v1.0.1 MIT
twig/twig v1.15.1 BSD-3-Clause
videlalvaro/php-amqplib v2.1.0 LGPL-2.1
whiteoctober/tcpdf-bundle dev-master 0e82ad1 MIT
willdurand/jsonp-callback-validator v1.1.0 MIT

Thanks for reading, Bye.

Symfony2 avoiding container injection

GoodBadHabits

Since I started using SensioLabs insight code analysis tool, I kept on getting a warning which advised against using Container Injection on my services. It was not the first time I heard this kind of message, Last year we submitted one of our projects to the SensioLabs team for evaluation, the client wanted to find out if we were following all the Symfony2 standards since he had enterprise ambitions for his project. Any ways the report was both good and not so great. We were doing okay with most of the stuff except for a couple of things:

  • Container Injection (Bad)
  • Fat controllers (Bad) – will cover this in more detail on another post
  • Unit testing (Not great) will cover this in more detail on another post

Besides those three things mentioned above, our team was not half bad – But it was an eye opener.

Being a victim of container injection is very easy, I did it because I only had to inject one service but still have access to all the services defined in the application – I mean really who would not want that, There are various reasons why you should not inject the container directly but the one I know of personally from experience has to do with Unit-testing your code. When want to start creating mock objects to test your service, it becomes a cumbersome job since your service only accepts 1 parameter and yet you are using more than 5 different services inside your one service – as the application grows so does the work of locating all these services being utilized so you can mock them. A lesson was learnt and a hard one indeed, But we never gave in – we just got better at it thanks to JMSDiExtraBundle.

What is JMSDiExtraBundle?

JMSDiExtraBundle adds more powerful dependency injection features to Symfony2:

  • configure dependency injection via annotations
  • convention-based dependency injection in controllers
  • aspect-oriented programming capabilities for controllers

NB: You can still inject individual services as arguments into your service using services.yml or services.xml

If you have not yet seen this bundle, I would recommend you head over to it’s website JMSDIExtraBundle, They have good documentation on both installation and usage – I will only cover the bit which shows how to inject services(DI) using the bundle as well as injecting config parameters into your service.

I have attached sample code to showcase how you can use JMSDIExtraBundle to define your service using annotations and inject relevant services. Please see blow.

Now lets explain what how the file is put together,  We first include the JMSDIExtraBundle into our class by using the following snippet:

use JMS\DiExtraBundle\Annotation as DI;

As part of your include you can be more specific if you just want to use “Inject” or “Tag”

use JMS\DiExtraBundle\Annotation\Tag;
use JMS\DiExtraBundle\Annotation\Inject;

Once the include is done, we can now give a name to our service – “This is what we would normal do via the services.yml or services.xml file”

* @DI\Service("my_project.send_account_created_email")
* @DI\Tag("kernel.event_subscriber")

Since our class is an Event Listener we need to also add a tag to let the service know how to plugin into the symfony kernel.

Lastly we inject our services into the service constructor, we only inject what we need  in the service and we can easily create mock objects to test the service constructor.

    /**
     * Class construct
     *
     * @param Logger      $logger  
     * @param UserManager $userManager
     * @param Mailer      $mailer
     * @param Templating  $templating  
     *
     * @DI\InjectParams({
     *     "logger"       = @DI\Inject("logger"),
     *     "userManager"  = @DI\Inject("my_project.user_manager"),
     *     "mailer"       = @DI\Inject("Mailer"),
     *     "templating"   = @DI\Inject("templating"),
     * })
     * @return void
     */
   
    public function __construct(
            Logger $logger,
            UserManger $userManager,            
            \Swift_Mailer $mailer,
            $templating
           
    )
    {
        $this->logger = $logger;
        $this->userManager = $userManager;
        $this->mailer = $mailer;
        $this->templating = $templating;
        return;
    }

Once more thing I wanted to show is injecting configuration parameters to the service.

    /**
     * From email name
     * @var String
     * @@DI\Inject("%mailer_from_name%")
     */

    public $fromName;  
       
    /**
     * From email address
     * @var String
     * @DI\Inject("%mailer_from_email%")
     */

    public $fromEmailAddress;    
       
    /**
     * Root path
     * @var String
     * @Inject("%kernel.root_dir%")
     */

    public $rootDir;

NB: You can also achieve all of this using services.xml or services.yml

I will not cover the Event Listener approach I used on this sample file on this post but be on the look out for a post dedicated to event listeners.

For more reading on Dependency Injection, I would recommend the symfony cookbook and this blog by Richard Miller.

Thanks for reading, Bye.

Book – A Year With Symfony

book

I spend most of my time reading the Symfony2 documentation, and chatting on the IRC channel and a couple of blogs every now and then. The one blog I like which offers a lot of insights into symfony has to be PHP & Symfony by Matthias Noback. He is always explaining the inner workings of Symfony2 and contributes to the original documentation.

The reason why I am mentioning this, it has do to with his new book called “A year of symfony“. It is a very good read for any Symfony2 developer and it covers the framework from the ground up. I downloaded the sample chapter one night and had my company buy the book the following day, it’s that good. Beware, it’s not a book for people new to symfony but a book for those already using symfony and want to improve their understand of the framework while writing beautiful releasable code.

What I have learnt from the book,

  • The kernel processes (from request to response – all the steps)
  • Event Listeners / Event Handlers
  • The Bundle code (Stop generating the bundle and build it manual, only add files you need)
  • Security of the application

I have had to change the way I code in symfony now for the better thanks to the guidelines the book provided, If you get a chance I recommend you get yourself a copy and also get your development team to get one also.

Thanks for reading, Bye.

Symfony2 using capifony for deployment

which

Once in a while you find great tools which not only make your life easier but also make programming fun again. Now in this case I am talking about capifony, which is an awesome tool for deploying your application on multiple servers using git.

What is capifony?

Capistrano is an open source tool for running scripts on multiple servers. It’s primary use is for easily deploying applications. While it was built specifically for deploying Rails apps, it’s pretty simple to customize it to deploy other types of applications.
capifony is a deployment recipes collection that works with both symfony and Symfony2 applications.

I hope that explain where it came from, capifony also offers two strategies for doing deployment.

  • deployment → scm → production (Production server must have access to git repo)
  • deployment → production (Plain copy of the code from your local to the remote production server)

In our case we going to use the first strategy, (deployment → scm → production). Please read the documentation on how to install capifony on your machine on their website. I will only share my script with you.

I create a small server(droplet) on my digital ocean account and performed the following  steps:

  • Added git access for my droplet server (using ssh keys)
  • Added ssh password-less login for my local  machine and the remote droplet server(More)

You will note I added multi version deployment which forces the script to keep the last 10 deployments on the droplet server.

NB: I have not tried this script on PRODUCTION yet and would recommend that you read up on the documentation some more until you understand every line on the script.

Thanks for reading, Bye.

Symfony2 Performing code analysis while you build your application

Glossy Robot with Magnifying Glass

Late last year I got a beta invite to use SensioLabs code analysis tool called Insight , However I did not have much time then, so I added it on my list of tools to check this year.

Fortunately I had some time to spare this month, So I created an account on Insight and registered a public project and did the analysis. The results of the analysis were both great and detailed enough to understand the possible Major and Minor bugs I had on my little application.

How does the tool work?

  • SensioLabs has come up with best practices standards which are recommended for Symfony projects, Your code gets checked against these best practices to make sure you do not deploy a security vulnerable system on production.
  • They detect dead / deprecated code.
  • They look at possible performance bottlenecks.
  • Commented code as well as ‘fixme’ comments
  • Git integration (I tested it with github)
  • Team collaborations (Business plan)
  • read more

SensioLabs offers a combination of packages, which covers just about every scenario from open source projects to big business( private projects). Check out the pricing plan.

This is a great tool to have for Symfony projects and will help big teams as well small teams to deal with bug risk code whilst still in development. I have not tried the paid plan yet but what I got from the free open source plan is worth raving about. It can only get better and hopefully they can lower the entry price from 60 to 30 euros for micro(Individual plan)  which I would definitely find viable.

 

 

Symfony2 Creating iCalender events

icalender

I am currently working on a Symfony 2 project that creates iCalender events which get sent out to recipients via email. I first hacked my own event script but after reading the RFC specifications I then realized how involved the protocol was – So I did a quick search on github and came across a nice php library which already handles most of the events specified in RFC document. (Do not re-invent the wheel unless the wheel is your business)

The library I found is called sabre-vobject which has some documentation to get you started creating your first event with minimal effort and fortunately it already supports composer and php namespaces already.

Now there is no bundle on knpbundle.com which deals with iCalender events currently which was the first place I checked, However since sabre-vobject  library supports composer and php namespaces it becomes easy adding it to your Symfony 2 project.

Step 1:

add the library to your project’s composer file, please see the attached screenshot below.

composer

You can perform your composer update there after and all is well.

Step 2:

Lets make the Vcalender class available as a service in our application, I prefer using JMSDiExtraBundle for all my dependency injection needs, but to configure this particular service I will use the services.xml approach because I do not want to add JMSDiExtraBundle annotations on the class in the vendor directory nor do I see a need to create another class to extend the original sabre-vobject VCalender class, Any ways see the xml configuration on the attached screenshot.

service

After you have done that, you can run a quick container debug to check if your service is appearing. After you have located your service in the container debug it’s time to test the service.

event

That should do it, if you need more information on the iCalender functionality I would recommend you read the RFC document as well the sabre-vobject documentation.

Thanks for reading, Bye.

 

PHP Composer: installation on ubuntu 12.04

In case you have not heard, but php has just gotten even better with a new dependency management tool. It’s not a package manager like pecl but a dependency management tool. I think the abstract text from the composer site says it better.

Composer is not a package manager. Yes, it deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default it will never install anything globally. Thus, it is a dependency manager.

Anyways, now that we have an idea about what composer is lets move on.I am planning on doing a series of posts which will highlight the benefits of using composer on your project.

I have only used the basic functionality which composer offers in symfony 2 but I am hoping together we can discover some of it’s hidden features.

Just a side note,  this posts assumes that you are running ubuntu 12.04 as your operating system.

Download Composer

So lets gets started, open your ubuntu terminal and type the following commands.

curl -sS https://getcomposer.org/installer | php

This above command will download  a file called composer.phar , It’s a PHAR (PHP archive), Please make sure you have permission to execute the command.

Install Composer

Once we have composer.phar we can start using it to download our libraries which our project dependents on. We can execute the following command to execute composer.

/usr/bin/php composer.phar --version

If you see a menu with options then congratulations it works.

However, we can make the installation better by installing it globally on the system and also adding it to our system path.

Please execute the following command to install it globally:

mv composer.phar /usr/local/bin/composer 

Notice: If you get permission issues please use sudo

Once you get it right, you should be able to execute the following command and get the composer menu.

composer –version

If you get an output like the one shown below, then you have successfully installed composer.

“Composer version fc3fbdeab3355c2c9d03e496c41b1a3bb9565a49 2013-11-20 14:17:10″

We will end this post here today, The next post will deal with configuring your project dependencies and other basic features offered by composer.