How to setup Atom for PHP Development

What is Atom and why it is awesome?

Atom is a hackable text editor. I normally don’t like the idea of text editors which need settings and different plug-ins installations to be some what equivalent to a complete IDE but after using Atom with some configurations and plug-in installation, my opinion is changed.

What now I think is that a hackable editor is actually good because it provide you option to only have functionality what you exactly need while still being very light-weight.

Using Atom as PHP IDE:

I came to Atom from Netbeans, when it became very slow and made overall system very slow. I never liked Netbeans’ non-smooth fonts on Ubuntu but didn’t find any good option. But after slowness issue, I tried Atom as text editor and then found it much more powerful by utilizing packages available. So now I use it for PHP development with useful features without making my system slow.

Please note that these packages will not make it equivalent to a premium tool like “PHP Storm”( in fact never compare other IDEs with JetBrains’ IDEs unless you don’t want to pay 100$+ for IDE. ), but still Atom with packages will be better experience in many ways as compared to other editors and IDEs. If you are currently using some text editor like notepad++ or brackets, or tools like Aptana or Eclipse, you will like Atom with these packages. And obviously your system will feel much better if you are coming from Netbeans.

Installing Atom:

Simply go to https://atom.io/ and download the build for your release and then simply install it. It don’t have any hard dependency like Netbeans need JRE. By just installing Atom, you can start using it as a simple text editor with smoother fonts and awesome themes.

Atom for JS:

Most of PHP developers also need to interact with JS and front-end. So you will want JS support as well. Atom come with some JS related packages already installed with Atom.

Atom Settings and packages:

To see atom packages, themes and other configurations then go to:

Top menu > Packages > Settings View > Open

or

simply press ctrl + , (control and comma key)

You should see this settings screen:

Now scroll down and find field labeled as Tab Length” and change its value to 4 instead of 2 as per PSR2 standard. ( http://www.php-fig.org/psr/psr-2/ )

Atom Packages:

In atom, you need to install packages to extend Atom and have more feature set. Here are some important packages listed below with their detail. Please note that Atom package can be installed using settings window as well as this command:

$ apm install <package-name>

PHP CS Fixer:

csfixeronsave

PHP CS fixer runs the “PHP Coding Standards Fixer” within your Atom Editor. Install this package but it will not start functioning. This package requires the “PHP Coding Standards Fixer” Cli build by SensioLabs wich can be installed using composer:

$ ./composer.phar global require fabpot/php-cs-fixer

Above package is abandoned so this one can be used:

$ ./composer.phar global require friendsofphp/php-cs-fixer

then go to settings provide path to php-cs-fixer and PHP. Also click on “Execute on Save” check box so that on save, it will format it according to psr2 standards.

Linter PHP:

linter-php error screen
linter-php error screen

Install this package so that your Atom know in case of any PHP syntax error  you make. It will show you proper error within your editor. This is very important unless you used to write PHP in conventional text editor.

It will work without any further settings if your php is accessible globally through command line. Otherwise you will need to provide PHP executable path in this package’s settings.

PHP Hyperclick:

Hyperclick provider for PHP. Open file when classname is clicked. This is simple and very useful package but installing it alone will not work. So you will also need to install dependency  that is Hyper Click (another package of Atom).

In case if it don’t work with “ctrl+click ” then try “alt+ctrl+click” .

Last words:

These are just few packages that I have installed and made my Atom editor  better, at least I no more miss Netbeans (which I was using for last ) for doing some work in modern framework like Laravel. But I expect a lot of more awesome surprising packages other than these. So keep exploring and let me know about your favorite atom packages in comment.

 

Configuring and using Laravel with MongoDB

This entry is part 1 of 1 in the series MongoDB

In this article we will see how to use MongoDB with Laravel (PHP framework). So first we need to install MongoDB and Laravel.

Laravel and MongoDB installation:

We will install Laravel and MongoDB one by one and I assume that you have PHP already installed with a web server.

Laravel Installation:

I assume LAMP environment is already configured. You can install Laravel simply through composer using following command if you have Composer already installed.

composer create-project laravel/laravel --prefer-dist

If you don’t know about composer or want to know more detailed installation and configuration of Larvel then Laravel documentation explained it in detail: http://laravel.com/docs/5.1#installation

MongoDB installation:

If you haven’t already installed MongoDB then MongoDB have separate guides for installing it own different Operating Systems. So check that: http://docs.mongodb.org/manual/installation/

Current version of MongoDB at this time is 3.x. But it you have MongoDB version 2.x installed and running on your machine then still feel free to use this tutorial, as it will work for 2.x as well and it have stuff related to 2.x difference in user creation section.

MongoDB driver for PHP:

PHP have official MongoDB driver that is called Mongo. It contains MongoClient class that is used by several packages which connect PHP with MongoDB.

You can install MongoDB driver on Windows OS using steps mentioned here: http://haafiz.me/development/installing-mongodb-driver-mongoclient-for-php-on-windows

To install MongoDB driver on ubuntu  or other Linux distributions, follow steps mentioned here: http://haafiz.me/development/installing-mongodb-driver-mongoclient-for-php-on-ubuntu

To check if MongoDB driver is successfully installed, try instantiating MongoClient class.

Laravel Package for MongoDB:

Laravel have several MongoDB related packages and some of them not work for Laravel 5.x (current versions at time of this writing). Based on several factors like number of contributers, number of commits, releases and documentation on github, simplicity and ease of use, I suggest using jenssegers/laravel-mongodb which is also knowns as Moloquent.

Installation:

To install for Laravel 5.1, install latest stable version using composer.

composer require jenssegers/mongodb

In config/app.php :

Add below line in providers array:

Jenssegers\Mongodb\MongodbServiceProvider::class,

And add in same file, add below line in aliases array:

'Moloquent' => 'Jenssegers\Mongodb\Model',

Moloquent Configurations:

In app/config/database.php, add MongoDB connection detail:

'mongodb' => array(
            'driver' => 'mongodb',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', 27017),
            'database' => env('DB_DATABASE', 'l5'),
            'username' => env('DB_USERNAME', 'l5'),
            'password' => env('DB_PASSWORD', '123456'),
            'options' => array(
                'db' => 'admin' // sets the authentication database required by mongo 3
            )
        ),

and make this mongodb connection, default connection.

'default' => env('DB_CONNECTION', 'mongodb'),

If you have installed MongoDB just now then you will not have Database, username and password to provide in connection info. For that purpose you need to first create database, username and password.

Setting up MongoDB Database and User:

To create a MongoDB database, you need to start, execute “mongo” from command line. To do so you need to add MongoDB bin directory to your system path. And then run:

mongod

This will run mongo server to listen calls.

In case you see error like: “data/db not found” , then that means that this path doesn’t exist on your system or don’t have appropriate permissions. So either create and assign appropriate permissions at that location or with appropriate permissions create DB data folder at some other custom location and give DB path like:

mongod --dbpath custom/directory/path

Once it is running, mongo server will be listening for client calls. So you need to run mongo shell client by simply opening another shell instance and run :

mongo

This will open mongoDB shell.

Creating Database in MongoDB:

Using mongo client shell, you need to create your database

> use dbname
> db.insert({"key":"value"})

By executing above statement, use statement switches DB to “dbname”, and assigns value “dbname” to variable “db”  so you can use your desired DB name. If “dbname” is name of existing database then it will switch to that database or else it will create that Database if atleast one record is added to that database.

Setting up First User and access:

If you are using Mongo 3.0 or above, first of all you need to switch to “admin” database and creating a user with administrative rights for all databases.

> use admin
> db.createUser(
  {
    user: "siteUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

You can replace “siteUserAdmin” and “password” from above code with your desired admin username and password. Role “userAdminAnyDatabase” is a special role for administrating all databases and this role is at “admin” database.

Once you have this Admin user on admin DB, you need to create user for your required DB, in our case “dbname”.

> use records
> db.createUser(
  {
    user: "recordsUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdmin", db: "records" } ]
  }
)

Here you can replace “recordsUserAdmin”,”password” and “dbname” with desired username, password and your intended database name. And this will set your admin user for that database.

If you are using MongoDB version 2.x then user creation is different. In version 2.x db.createUser() function is not present. You need to use db.addUser() like:

> use products
> db.addUser( { user: "user1",
              pwd: "password",
              roles: [ "readWrite", "dbAdmin" ]
            } )

So now you have DBname, username and password to put in you Laravel app/config/database.php

Extending Models from Moloquent:

Only thing that is left is to extend your models from “Moloquent” instead of “Eloquent”.  So a typical model will look like this:

<?php
namespace App\Models;

use Moloquent;

/**
 * Category Model
 *
 * @author Hafiz Waheeduddin
 */
class Category extends Moloquent
{
 public function tasks()
 {
 return $this->hasMany('App\Models\Task', 'category_id');
 }
}

So after that you can simply run most of queries of query builder through category model. And can utilized ORM in similar way as Moloquent supports many types of relationships, so you can utilize them too.

Moloquent Detail and Documentation:

Moloquent have very good examples at github to understand it and use it. So for Moloquent usage, reference and understanding, please check moloquent github page .

Installing MongoDB driver for PHP on Ubuntu and other Linux distributions

Mongo is official MongoDB driver for PHP. Here is detail of this driver on php.net:  http://php.net/manual/en/mongo.manual.php . Mongo include MongoClient class which is required to connect MongoDB and required by several packages that bridge between MongoDB and PHP.

MongoClient works on almost all of Operating Systems including Windows, Mac OS X, Unix, and Linux; little- and big-endian machines. No matter 32 or 64-bit machines. PHP 5.3 through 5.6. To install it, there is a “mongo” package on PECL.

To install PHP Mongo on Linux, follow below mentioned steps:

  1. Run this command:
    sudo pecl install mongo
  2. If response of above command is error with text “phpize not found” then you need to first run this command and then above one. Please note that this command is useful on Debian based distributions, for others please use appopiate command accordingly :
    sudo apt-get install php5-dev
  3. Then add following line to php.ini
    extension=mongo.so
  4. Then you need to restart your apache or nginx . If you are using apache then use following command to reload it.
  5. service apache2 reload

    After this hopefully your PHPClient class will be working fine and you can test your code which use MongoClient class.

    In case of any problem, feel free to let me know in comments section.

Installing MongoDB driver for PHP on Windows

 

mongoPHP-logo

MongoClient class is included in “Mongo” that is official MongoDB driver for PHP. MongoClient class is required to connect MongoDB and required by several packages that bridge between MongoDB and PHP. Here is detail of this driver on php.net:  http://php.net/manual/en/mongo.manual.php

Mongo works on almost all of Operating Systems including Windows, Mac OS X, Unix, and Linux; little- and big-endian machines. No matter 32 or 64-bit machines. PHP 5.3 through 5.6. To install it, there is a “mongo” package on PECL.

To install Mongo for Windows, you need to do following steps (Tested with Windows 7) :

  1. Download this package from PECL website manually. Go to PECL Mongo package and choose latest stable version’s DLL by clicking on DLL link.
  2. Choose Thread safe x86 version, even for 64 bit system and download it. 64-bit version didn’t work for some people while x86 on 64-bit system worked fine so use download x86 thread safe version.
  3. Extract the zip file that is just downloaded, and place it in your PHP’s ext (extensions) directory. Ext directory can be find through phpinfo().
  4. Once placed in PHP’s ext directory, open your php.ini file and add follwing line and save it:
    extension=php_mongo.dll
  5. Then restart your apache server and test your code which use MongoClient class. It should work now.

In case of any problem, feel free to ask in comments.

API Testing: Installing and Using Codeception

This entry is part 3 of 3 in the series API Testing

In this post, we will have a look on how we can use Codeception for API testing. First we need to install codeception.

Installation:

Here is Codeception’s quick start guide that show multiple ways to install codeception. Here we will be installing through Composer, you can follow any other method as you like.

First go to directory where you want to install Codeception and place your tests. In my case that directory name is “app1”.

composer require "codeception/codeception:*"

or

php composer.phar require "codeception/codeception:*"

It will take some time, and fetch codeception. Once it is done, you will be able to use codeception command line tool. Try running codeception following command to make sure that you have codeception installed.

vendor/bin/codecept --version

Setup Codeception:

Here is something you need to do to setup your codeception testing environment. Run following command from root of your app directory.

vendor/bin/codecept bootstrap

It will create ‘tests’ folder at root of your app directory. This is where all your tests files and information will live. This tests directory will have many directories including acceptance, functional and unit . These directories are related to different types of tests suites.  We need to have api test suite, that isn’t yet created here. So let’s create that now.

vendor/bin/codecept generate:suite api

ok now in tests directory it will have a new directory named “
api
” . That will have Api Test suites in it. Ok, before moving further, let’s first get rid of this long path “vendor/bin/codecept” so that we can just use “codecept” command instead of whole path.

So if you are on linux, ubuntu you would probably be interesting in installing codeception globally. So that you can simply use “codecept” command from anywhere. Here is how you can do this: http://stdout.in/en/post/install_codeception_globally_in_ubuntu

If you are on windows then you can simply add it in your system path.

Ok once done that you can now to use codecept command you can simply say “codecept” and it will work.  Simply try following command from anywhere.

codecept --version

Now you are ready for next things but let’s first understand directory structure of codeception.

Codeception Directory structure:

If you go in “tests” directory which is created as a result of “codecept bootstrap” command. There you will see following directory structure.

  • _data
    This directory can have DB file if you need to use that.
  • _output
    This directory contains output of tests in case of failure.
  • _support
    This directory can have helpers if you write that to support your tests.
  • acceptance
    This directory is useful if you need to write acceptance tests.
  • api
    This directory is useful if you are writing api tests. This directory is not present by default but it will be created as result of api suite generation command.
  • functional
    This directory is useful if you need to write functional tests.
  • unit
    This directory is useful if you need to write unit tests.
  • _bootstrap.php
    This file is useful for autoloading any file that you want to include.
  • acceptance.suite.yml
    This file contain configuration of acceptance suite.
  • api.suite.yml
    This file contain configuration of api suite.
  • functional.suite.yml
    This file contain configuration of functional suite.
  • unit.suite.yml
    This file contain configuration of unit suite.

Also in api directory there is _bootstrap.php . It is useful if you want to include and autoload any file inside api suite only.

API test suite configuration:

Open api.suite.yml and add PhpBrowser helper and add URL, it should look like something like this:

class_name: ApiTester
modules:
    enabled: [ApiHelper,PhpBrowser, REST]
    config:
        PhpBrowser:
            url: http://localhost/app

Note: Above code snipper for yml file contains 4 spaces per tab and not tab character.

Laravel or PhpBrowser module :

If you are using Laravel, then you can add Laravel module instead of PhpBrowser. So that in case of error, if you are using Laravel module then error message will be more debug-able than a 500 error that can be seen on browser screen too. I was previously using Laravel module and error was more clear with better insights but problem is that Laravel module is much slower than PhpBrowser module so I switched to PhpBrowser. However if you have good RAM and not yet concerned about speed of execution of your test cases, specially if they are less than 50, then using Laravel module is better option. So it all depends on you.

Writing Test Case:

There are two ways to write test cases based on two types of files. Cept and Cest. Cept is a scenario-based format and Cest is a class based format. Actually it depends on how you are comfortable writing code for test cases. In strucute way or using classes. I prefer and recommended class based format because it will give you OOP power for writing more test cases with less code in long run.

So generate your first Cest file by this command:

codecept generate:cest api CreateUser

Now open that file and put some code in that as below.

wantTo('create a user via API');
        $I->amHttpAuthenticated('service_user', '123456');
        $I->haveHttpHeader('Content-Type', 'application/x-www-form-urlencoded');
        $I->sendPOST('users', ['name' => 'davert', 'email' => 'davert@codeception.com']);
        $I->seeResponseCodeIs(200);
        $I->seeResponseIsJson();
        $I->;seeResponseContains('{"result":"ok"}');
    }

}

Here $I contains the object of ApiTester that is respresting a user state who is testing a scenario.

Running Test Case:

If you are running testcase first time in api suite, then in your api directory you will not have api tester file. You need to generate that so run following command:

codecept build

Then run

codecept run api

It will show you error or failure if at mentioned URL you will have not have intended path or functionality working. If you want to see what’s going on behind the scene for your test case then use -vv or -vvv for even more verbose.

codecept run api -vv

To know more about Codeception, simply check codeception documentation: http://codeception.com/docs/10-WebServices

However, if you want to know more about Automated testing, better ways of testing, why and how to write tests. Then I recommend reading Laravel Testing Decoded by Jeffrey Way. And if you are a PHP guy then I even strongly recommend reading this book because you will most probably be lacking something that is in this book.

You’re probably familiar with Jeffrey’s Laracast, this book is even better than that to understand Testing and follow better approaches to both development and testing.

Import larger SQL files into MySQL

Larger SQL files can be imported into MySQL using different ways. I am listing 3 common ways here.

Using PHPMyAdmin by increasing upload_max_filesize:

Most  commonly used tool for MySQL is PHPMyAdmin but problem is that PHP have upload file size limit so files larger than that can’t be uploaded but in PHP Configuration file (php.ini), there is  “upload_max_filesize” limit that can be changed. So if you want to import larger file using PHPMyAdmin then you need to modify php.ini file.

You can find php.ini file path through phpinfo(). So go to php.ini, and find upload_max_filesize you will find something like:

   ; Maximum allowed size for uploaded files.
   ; http://php.net/upload-max-filesize
   upload_max_filesize=2M

Replace upload_max_filesize value with file size larger than your SQL file that you want to import. So if you want to allow file of 100 MB to be uploaded , then you should replace above line of code with:

   ; Maximum allowed size for uploaded files.
   ; http://php.net/upload-max-filesize
   upload_max_filesize=100M

Restart your server, most probably you will be using apache2. So if you are on Linux then use this command:
sudo service apache2 restart

If you are not on Linux and using some other package for PHP then restart your server accordingly. And now you should be able to upload bigger files hence you will be able to import bigger SQL files.

 

Using Command line:

Most simplest and my favorite to import  larger SQL files is command line usage because if you have access to command line then it can work almost everywhere. From your terminal or Command prompt based on Operating System (OS) you are using, execute following command:

mysql -u <username> -p<password> <DBName> < filename.sql

Here replace <username> with your DB username, <password> with your DB password, <DBName> with Database name and filename.sql with your SQL file’s path you want to import.  Please note that there shouldn’t be space between -p and password.

Using Desktop Tool:

Simply use a desktop based tool instead of PHPMyAdmin. If you are importing SQL file on a server where you can only use SSH to do anything or you are using it on a shared hosting then desktop tool is not always an option for you unless your DB is accessible from remote connection.

However if you can use Desktop based tool then you should desktop based tool as they are much more flexible and importing large SQL file is not a problem. So in this regard, there are plenty of free and paid tools. Navicat for MySQL is a nice tool but it is paid and costly. So probably you will be interested in free GUI tools like MySQL workbench.

If you guys found something unclear or some mistake in the content then feel free to let me know in comments section.