This week in my company (Persol process technology Viet Nam). My manager give me one task – research and find a best framework to write RESTful API with Php. When research, I found a Php Laravel framework.
Have a solution, but I’m still have question: why Php Laravel is so strong?. What I can do with this framework?. When we want to build a fast service API, the Php Laravel is not a bad choice.
Today, I write this post, want to share my little knowledge about Laravel. HOPE THIS HELP!.
1. The validator in Php Laravel
That’s the first thing I want to share about Php Laravel. When creating a API, the most important thing developer should care is “How can validation a input paramter?”.
Why?. That’s easy to understand, if we not handle API input handle input parameter, we will get in big trouble.
Let me show you an example. If the column to save company name in postgres database is character varying, and this accept only 50 characters. If user using the browser and UI to send a request, there is no problem. But if someone developer tries to cheat your system. They using postman, send a compy name they want?. The system will not work correctly. The data input in system is not correct.
That explains why we always validation an input parameter in API!. Back to the main problem.
Let me show you an example, we have API to update list userId information. The condition is they can’t null, can’t empty, can’t contain duplicate value. When I use Java 8 to write an API. I will do:
// In java // The userId can't be null if (userIdsArr == null) { show error, they can't null terminal } // The array can't be empty if (userIdsArr.length() == 0) { show error, they can't empty terminal } // Check if list userId duplicate if (checkDupilcate(userIdsArr)) { show error, they can't contain a duplicate } /** * Check item in array is duplicate */ public void Boolean checkDupilcate(Array userIdsArr) { Set<T> set = new HashSet<>(); return list.stream().allMatch(t -> set.add(t)); }
That’s make me tired, although they are very simple validation, like null, empty. Let make a change. If I use Laravel Validator, let me what I can do
// In Php laravel validator protected rules [ 'userIds' => 'required|array', 'userIds.*' => 'integer|distinct|min:0' ]
Yes, that’s all the things I do to handle an input parameter. With required, Php Laravel will handle for me it can’t null and it will exist in the parameter.
With a distinct, the Php laravel will ensure that all items in the array will unique. Easy boy!. Furthermore, with an integer, all items should be a number. If you send a string, the error will show.
OMFG, that’s very easy, clearly (because it look like a natural language). Hmm, now I love a Php Laravel so much. =)).
2. The database migration
Currently, Php Laravel supports a Database migration. If you don’t know what is this, I will explain it to you.
The imagination that your team developed production in one month with PostgreSQL, and now they want to change to MySQL. What’s happened?.
If you don’t have a Php Laravel migration, what should you do?. First, we will create a statement in all database, if the database have more than 200 tables, that’s a nightmare.
With migration, there is no problem in here. Just enable a setting in php.ini. Setup a information for environment file and run migration. We will get a same database, in MySql. But wait, the migration in php is very easy to write. Like that:
// In Php laravel migration // That is easy to understand, easy to extension. And the most important thing // They can run every where class CreateUserTable extends Migration { Schema::create('users', , function (Blueprint $table) { $table->increments('user_id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->timestamp('password_experied')->nullable(); $table->timestamp('created_at'); $table->decimal('created_by', 11, 0); $table->timestamp('updated_at'); $table->decimal('updated_by', 11, 0)->nullable(); $table->decimal('delete_flag', 1, 0)->default(0); }); }
// A environtment file setup // Just change this file when database change DB_CONNECTION=pgsql DB_HOST=127.0.0.1 DB_PORT=5432 DB_DATABASE=postgres DB_USERNAME=postgres DB_PASSWORD=password
3. DB transaction
With Java Spring, with @transaction taglib, we will handle a commit, rollback a transaction. But with Php Laravel, you can use DB::transaction.
That’s flexible to control a transaction. Because it’s closure function. Let see example below:
// Php laravel transaction control DB::transaction(function () { DB::table('users')->update(['votes' => 1]); DB::table('posts')->delete(); });
You may use the transaction
method on the DB
facade to run a set of operations within a database transaction. If an exception is thrown within the transaction Closure
, the transaction will automatically be rolled back. If the Closure
executes successfully, the transaction will automatically be committed. You don’t need to worry about manually rolling back or committing while using the transaction
method.
4. Summary
For any guys who never use Php Laravel. Please listen to me: just try use it for one time. It’s not make you dissapoint. After use Php Laravel, we will know the way to build a fast API service (with a high quality). That’s very helpful. Good luck to you!.
I will write more post about Php Laravel and PostgreSQL database. You can read it in here.