Building RESTful Web Services in PHP7


Here is the book I have written recently on RESTful web services in PHP 7. The title is Building RESTful Web Services in PHP7 and is available on Amazon. You are probably wondering that why another PHP book. Why about RESTful web services. Many people consider RESTful web services as hitting a URI and getting JSON in response. However, this is a misconception. RESTful web service is more than that. And when it comes to Building RESTful web services then there  are numerous important things to consider.

Although there are already books on PHP and RESTful web services, this book is important because PHP and its ecosystem has evolved. “PHP7” in the title is to tell that we are talking about modern tools and ecosystem of PHP. Let me provide you detail of book in structured way. Let’s discuss different aspects of the book one by one.

Who is this book Useful for?

  • Anyone who have some basic PHP knowledge and want to build RESTful Web Service.
  • Developers who know basic PHP and have developed some basic dynamic website.
  • Developers who know basic PHP and have developed some basic dynamic website.
  • Developers who have learned PHP and worked mostly in Open source CMS like WordPress etc.
  • Developers who have used modern frameworks but not sure about critical pieces required to build RESTful API.
  • A seasoned PHP Developer, have created very basic API that returns data but want to make himself familiar with how it should be done according to REST standards and how it will work when authentication etc comes in and how to write tests for it.

What will Reader Learn?

  • REST API architecture and its benefits
  • How to write RESTful API web services in PHP7
  • To address security related issues in a REST API
  • Importance of automated testing and to write tests for API endpoints
  • Will be introduced to Micro-services architecture
  • Will understand security flaws in our API endpoints and tackle them effectively
  • The working of Lumen micro-framework and writing RESTful web services in it

Content of Book, Chapter by Chapter:

Chapter 1 RESTful web services, Introduction and Motivation:

This chapter is about introduction to Web Services, REST Architecture, RESTful Web Services, its comparison to other Web Services. HTTP Verbs, RESTful endpoints. It also explains RESTful web services concept by the use of Blog example and then talk about Response format and Response Code.

Chapter 2, PHP7, To Code It Better :

This chapter includes new features or changes on PHP7, which we will either use in this book or which are very important and worth discussing. As new features include features related to generators as well so introduced generators to user. Although generators were there already but rarely people use it. So this chapter also tells us about generators with examples.

Chapter 3, Creating RESTful Endpoints :

This chapter is about creating REST API endpoints for CRUD operations of a blog post in Vanilla PHP. Will also tell manual way of testing API endpoints through a REST client named as Postman.

Chapter 4, Reviewing Design Flaws and Security Threats :

In this chapter we will review what we have built in Chapter 3 and will highlight problems and flaws in it so that we can later improve that. It will include some security flaws as well. Some of the flaws and security threats in our application also fixed in this chapter while told about some of threats solution but not solved in this chapter but pointed towards open source package.

Chapter 5, Load and Resolve with Composer, an Evolutionary:

This chapter is about an evolutionary tool in PHP eco-system that is composer.This is not just an autoloader or package installer but a dependency manager. So one knows more about composer in this chapter.

Chapter 6, Illuminating RESTful Web Services with Lumen:

In this chapter we will introduce a micro-framework named Lumen. And will rewrite our RESTful web services endpoints in this micro-framework and will review how this tool will significantly improve our development speed as well as application structure.

In this chapter, users can first understand the Lumen framework, its components and then its usage to create RESTful web services’ endpoints.

Chapter 7, Improving RESTful web services:

This chapter will improve what is done in chapter 6 and we will learn and improve lot of stuff. User will create authentication, will make Transformer to separate how JSON structure should look like. Also user will improve web service in terms of security and will also learn about SSL.

Chapter 8, API Testing – Guards on the Gate:

This chapter introduces the need of Automated Tests. Will introduce different type of tests and then focus on API testing and teach user an automated testing framework named CodeCeption and will then write API tests in that testing framework.

Chapter 9, Microservices – An introduction

This chapter is about micro-services architecture. So we will understand and see benefits and challenges of Micro-services and will look into some of possible solutions or trade-offs. Introducing a new topic at the end of book normally doesn’t make sense. However, here this chapter point user towards Micro-services architecture that seems like the logical next step about how RESTful web services should be organized.

 

This is how I could present the content of the book. Feel free to let me know of your opinion. If you liked the book and want to buy then you can buy it from amazon:

Fix Uncaught ReflectionException: Class log does not exist …/laravel/framework/…

I again got this error which left me no clue of what happened wrong and how can I fix it.

PHP Fatal error: Uncaught ReflectionException: Class log does not exist in .../vendo/laravel/framework/src/Illuminate/Container/Container.php:741

I tried to find solution on google for a while and came to know that this don’t tell what acually went wrong. There can be different things which can be in different case. And you will find nothing other than someone will be telling that this error just mean something crashed earlier on before that interface was bound. So it tells nothing useful.

I found different reasons for this, but most commonly it was after you updated something in your system, which effected some extension of php or something else went wrong.

Here I am not going to dig deeper into why it happened because there can be lot of different reasons, I am just trying to tell a way by which I came to know the reason and fixed it. It happened to me twice in last few months and I found nothing on stackoverflow so that’s why I am writing it here.

So here are steps to find the reason and fix:

  1. Good thing about Laravel is that it checks some obvious dependencies which are required for Laravel to function properly. So go to some other directory and try installing Laravel’s same version there.  You can install it using
    composer create-project --prefer-dist laravel/laravel blog

    while in my case I was using Laravel bootstrap so I ran

    composer create-project graham-campbell/bootstrap-cms --prefer-dist -s dev
  2. It will show you missing dependencis, so you can see the dependencies and try to resolve them by installing missing extensions. In my case it was ext-mbstring  missing and in someone else’s case it was php-mysql extension missing. So install whatever extension is missing in your case.
  3. After installing extension don’t forget to restart apache:
    sudo service apache2 restart
  4. Once you have those extensions installed and your able to complete Laravel installation, go back to actual Laravel installation directory where you were actually facing above mentioned issue.
  5. Once you are there, give all permissions to `storage` and `bootstrap/cache` directories in Laravel installation by doing:
    sudo chmod 777 storage -R
    sudo chmod 777 bootstrap/cache -R
  6.  Now execute following command:
    php artisan clear-compiled
  7. If you see error like:
    PHP Fatal error: Trait 'Illuminate\Auth\Access\HandlesAuthorization' not found in ...dynamic/bootstrap/cache/compiled.php on line 737
    Script php artisan clear-compiled handling the post-install-cmd event returned with an error[RuntimeException]Error Output: PHP Fatal error: Trait 'Illuminate\Auth\Access\HandlesAuthorization' not found in /var/www/html.../bootstrap/cache/comp

    Delete the contents of the bootstrap/cache folder, then run

    php artisan app:update 

    and try running

     php artisan clear-compiled

    again.

  8. After doing so just run:
    composer dump-autoload
  9. And then go to your browser and try to reload. Most probably it should be working as this is how I had it working twice.

In case it still don’t work, then post it in comment and we can try to dig into that.

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.

Technical checklist: How to start coding new project

Even a fresh graduate out of university or a college student can do programming. They can create websites, mobile applications, and much more stuff. But inexperience person with quick start of a project without considering important aspects can result in a lot of problems. In fact, seasoned programmers who don’t consider important factors before starting project end up with similar problems. Remember, experience is although listed in number of years, but maturity, quality and efficiency  don’t come only by understanding and fixing problems but also not doing same mistakes again and again. Maturity come by learning from own and others mistakes.

So whether you are a seasoned programmer or a new programmer, here is a check list having some important things to consider before starting your next project. Here I am more focusing on programming related stuff not project management side.

Understand the big pictures:

Even though we are not focusing on project management size but at any level understanding the big picture is very much important. Even if your work is a small part of something big, still you should at-least understand how your work is going to interact with and will be integrated with rest of system. This will let  you avoid many small mistakes which can later appear as big problems. Also based on big picture you can better decide about technology and approach for your work.

Some documents are helpful:

Yeah I know lot of documentation sometime overshadow actual development process. I am not asking for that. But you should at-least have some sort of  diagrams which clearly state important flows, rules and relations. If that is not possible then should have a bullet point document so that your client can understand what you are going to do before seeing something actually coded and working in-front of him and believe me it will be really helpful for you to develop something that is decided and listed instead of developing while thinking about missing pieces.

Have  a DB diagram:

If you are using a database in your project then you should at-least have an initial DB diagram ahead of coding business logic to keep you on track. Try to create a DB diagram even if you have decided to not making any other diagram.

Write and run Test Cases:

I understand that most of programmers don’t have time for writing test cases. It consume time to write more code for testing your code. But there are already such testing frameworks which can make your work a lot easier. It will still take time to write tests but it will really rescue you in case of any major change requested by client or due to some mistake . In the middle of project, developers hesitate to change existing functionality because that can break some parts of system that no body will know before shipping code that can break while in production.

But sometime it is crucial to do such major changes so here automated testing tools can rescue you. These test cases let programmer know that where change is effecting. So that programmer can fix those places before shipping and rerun all test cases. It provides much more confidence to developer over his code.  It is up to you  that which type of testing you want to use and which framework you want to use for that.

In fact, in my last project client 2 times asked for such major changes and we already had test cases written, so after doing changes I just ran test cases and it showed me the test cases failures. So I fixed those parts accordingly. So after doing all changes and fixing everything I again ran test cases and at the end I was confident that now there wasn’t any remaining broken thing due to that major change.

If still not convinced that Automated Testing can make your life better, then see a this question answer format article: Why to write test cases using Automated Testing tools?

Use Latest Stable version:

Always use latest stable version of a framework or library if possible. Because the product or project you are developing right now will be in production after some time and then it will remain in production for much more time. So use latest stable version available so that you or product owner don’t need to upgrade libraries or frameworks again and again and can utilize latest features from day one.

Version Control is always important:

Version control tools are not only useful for keeping versions and history but it can be useful as a tool for auto merging different team-mates’ work too. Other than that, it is very helpful for having an on-line backup other than on your system so one can access it from anywhere as well as it is safer to not rely on single system.

Use Dependency Injection:

If your framework or library provide a way of dependency injection then use that or get dependencies available for your class in class’ constructor instead of separately instantiating objects in different methods of a class. Because this way you will not only know your class dependencies easily but you can also replace them easily if you want.

Use Interfaces:

Try to always use interfaces instead of concrete classes for instantiating objects. Interfaces make your code loosely coupled and let you swap parts of system much more easily.

Use thinner Controller:

If you are using MVC pattern then your controller must only have, required things and should be thinner. And reusable stuff should never be in controller but in library, helper or model etc.

Respect SOLID:

As per wikipedia, SOLID (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion) is a mnemonic acronym introduced by Michael Feathers for the “first five principles” named by Robert C. Martin in the early 2000s that stands for five basic principles of object-oriented programming and design. Here you can find more information about SOLID. https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)

However what I want to say is that SOLID will make your programming and work better. And your code will be much more flexible and clean.

So these are few things which are in my checklist, let me know if there is something else that you think that it should be added in this list. I will try to later attach detailed articles to most of these points which need more clarification or detail.

Thanks.

Installing Laravel on Windows

I wrote an article on Installing LAMP environment on ubuntu cloud instance that somebody found helpful and he requested me to write for Laravel installation and configuration for Windows development machine. So here is step by step guide.

XAMPP:

I assume you have XAMPP or equivalent installed and running. If not then download it from https://www.apachefriends.org/download.html

 Composer:

Then second thing you should have is composer. Composer is a dependency manager for PHP. To check if you already have composer installed, open command prompt and type following command and hit enter:

composer –version

If you see composer version then it is installed, but if you don’t see that and instead see:

‘composer’ is not recognized as an internal or external command, operable program or batch file

Then you need to install composer. So download and install composer by following steps from here: https://getcomposer.org/doc/00-intro.md#installation-windows

Installing Laravel via Composer:

We will install Laravel using composer. But first you need to switch to your www root directory.  For XAMPP it will be htdocs folder in your xampp directory.

Type following command in command prompt and hit enter:

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

This will start downloading laravel and its dependencies that may take few minutes.

And it is installed. To test it hit:

http://localhost/laravel/public/

And you should see Laravel welcome screen. Once you have Laravel installed and running, Laravel website has a good documentation that you can follow. And if you want even better source than that, Laracasts is the place to start.

API Testing: Selecting Testing Framework ( PHP Unit vs Codeception vs Behat )

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

In previous article of this series, we discussed that why you should use automated testing, specially if you are writing APIs.  So now it is time for selecting right tools for doing our API testing.

Available Testing Framework:

As there are application development frameworks to make your life easy, there are also many different testing frameworks which can be used for automated testing. Now point is that what framework you should use? It all depends. All have their pros. Important is what you want to achieve, how much time do you have.  When I was first time writing tests to test APIs, I took  4 days from client to find tool and write test cases so that, it can save me from manually testing all API endpoints and test cases before committing my code and leaving office. Yes, if you will not have automated tool then you will need to do lot of manual testing every day.

Anyways, my project was in Laravel 4 and by doing some search on Google, I came with three PHP based testing frameworks.

  1.  PHP Unit: Because it is basic and starting from basic is easy.
  2. CodeCeption: BDD-style PHP testing framework, it was more than basic, but can be used for different sort of testing.
  3. Behat: It is a tool for Behaviour driven development. It means that test are ;written in human readable sentences that describes your application’s features.

Here is more detail about them with Pros and Cons:

PHP Unit:

PHP Unit is basic testing tool and first thing that can come to mind or (at time of writing) first record  come in Google search result if you search “PHP testing”. And PHP Unit older than all the above mentioned, its initial released was in 2004, so that means it is mature enough.

Pros of PHP Unit:

  1. It is mature and very popular and that’s why good documentation, lot of tutorials and lot of threads on Q&A boards and on forums.
  2. It is basic and basic is often simpler to start, when you are doing some thing first time or new in something.
  3. PHP Unit is probably one of the best known tool for Unit Testing, as clear from its name too.

Cons of PHP Unit:

  1. PHP Unit can be the best tool for Unit testing but API testing is different, so it is probably not better to use it for API testing or acceptance testing because, these are higher level different than Unit testing.
  2. PHP Unit is very limited. It is easy to understand the basic but if you need more than that and want to higher level stuff then either you will need to integrate different tools with PHP Unit or will need to write lot of code to write higher level tests like API testing.

Codeception:

codeception-logo

Codeception is known as BDD-style testing framework. If you go to codeception.com you will be able to see lot of different examples  for different type of testing. It is something that can fit to one’s needs in very different ways.

Pros of Codeception:

  1. It is more than basic with lot of features available for different type of testing, no matter if it is low level like Unit testing or higher level like API testing or if it is BDD.
  2. Even with lot of feature it is not that much difficult, it is easier that can be seen from homepage of Codeception.
  3. It have separate modules for many PHP frameworks like Symfony2, Laravel4, Yii, Phalcon, Zend Framework. It don’t mean that it only support these frameworks but if you are using these frameworks and use its these modules, it will provide better features like errors will be more clear, and debugging will be easier however that can result in more memory usage in some cases.
  4. It provides support for different other testing frameworks if you want to use them with it.
  5. Its Test Cases are written in PHP so programmer don’t need to know a different language for that.

Cons of Codeception:

  1. Codeception is no doubt an awesome tool but it probably don’t have as much documentation and resources compared to PHP Unit. However as it is powered by PHP Unit so one can go to that level to do something at low level too.
  2. Codeception is no doubt easier but not as much simpler and easier to configure and start as PHP Unit can be.
  3. Codeception is feature rich but it is still BDD-style tool not actually aimed at BDD and its test cases are written in PHP, so if you have a QA team who can’t write PHP then they can’t write different feature or scenarios of the system without touching PHP or programmer will need to write all those test cases.

Behat:

behat_logo

Behat is a BDD tool. And this is the purpose fo which mainly Behat is used.

Pros of Behat:

  1.  As Behat is BDD framework so it’s language for writing test cases is very human friendly and person with no programming experience can write features easily.
  2. Like Codeception, Behat is feature rich tool.
  3. Behat test cases and cleaner and maintenance of tests in Behat is easier because a layer on which test case scenarios are being written is different than where these scenarios definitions are written.

Cons of Behat:

  1. Behat is no-doubt awesome tool for BDD but for things like API testing it will probably need more tools to integrate with it.
  2. If you don’t have a separate QA team and one programmer is writing tests then writing test case scenarios and its definitions separately will be bit more complex .
  3. Programmer need to understand Behat’s human friendly syntax called Gherkin.
  4. Due to more layers involved, for programmer who haven’t used it before, it can take more time to write test cases and understanding this tool.

Conclusion:

As told above I had 4 days to look into Testing frameworks and writing some test cases for API testing and framework I was using was Laravel 4, so what I started using was Codeception. It isn’t about winner or loser, it was about which testing framework is right for you based on your requirements and time you have to learn and configure it.

I picked Codeception over PHPUnit because spending a little bit more time on configuring and learning  Codeception, I was able to save much more time during writing test cases for API Testing. And I picked Codeception over Behat because Codeception seemed to have less steaper learning curve than Behat because Codeception’s test cases are written in PHP instead of Gherkin. And I didn’t have any requirement for Gherkin (human friendly syntax) as I was the only person who was writing Test Cases.

So this was my choice based on my requirements but feel free to choose different testing framework based on your set of requirements. In next part of this series “Testing API”, we will look into how to install and configure codeception and will look into its different files and directories.

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.