Thursday, 23 February 2017
Build Restful API with PHP and Laravel
The PHP Framework For Web Artisans
Introduction
Laravel is one of modern php framework that adopt many features in PHP code, provide a powerful templating engine and moves the code according to the CLI called artisan. Laravel is easy to udnerstand and it is built on top of a number of components from Symfony, one of PHP's most mature framework. To continue working with this tutorial, you need to have a composer, which basically use in PHP dependency manager. The installation can be further explore on this link. Click here
Tutorial
To get started, first off lets go to app/routes/web.php and then configure or modify according to code below :
Route::get('names', function() { return array( 1 => "Hassan", 2 => "Malik", 3 => "Syimir" ); });
Run the server using CLI command 'php artisan serve' to start remote server. Basically our local host. Then access this address http://localhost/names in our browser, you should see the output comes in array of json.
{"1":"Hassan","2":"Malik","3":"Syimir"}
However we might want to add or browse of endpoint for specific id, the coding file can be written as below :
Route::get('names/{id}', function($id) { $names = array( 1 => "Hassan", 2 => "Malik", 3 => "Syimir" ); return array($id => $names[$id]); });
So, if we browse in a specific eg. http://localhost/names/3, you should get the following in JSON format such as below :
{"3":"Syimir"}
Generally, the example shown are to create endpoints that respond to GET requests. You can change GET request to POST request, for instance, use Route::post instead of Route::get.The idea is to give exposure of Restful APIs using laravel framework and able to use resources efficiently.
Wednesday, 22 February 2017
Working with Git
Terminology
Here’s the git terminology:
- Master - the repository’s main branch. Depending on the work flow it is the one people work on or the one where the integration happens
- Clone - copies an existing git repository, normally from some remote location to your local environment.
- Commit - submitting files to the repository (the local one); in other VCS it is often referred to as “checkin”
- Fetch or Pull - is like “update” or “get latest” in other VCS. The difference between fetch and pull is that pull combines both, fetching the latest code from a remote repo as well as performs the merging.
- Push - is used to submit the code to a remote repository
- Remote - these are “remote” locations of your repository, normally on some central server.
- SHA - every commit or node in the Git tree is identified by a unique SHA key. You can use them in various commands in order to manipulate a specific node.
- Head - is a reference to the node to which our working space of the repository currently points.
- Branch - is just like in other VCS with the difference that a branch in Git is actually nothing more special than a particular label on a given node. It is not a physical copy of the files as in other popular VCS.
Example Cloning and Fetch from remote repository
Git & GitLab Repository
What is Git?
Git is a version control system (VCS) for tracking changes in computer files and coordinating work on those files among multiple people. It us primarily used for software development, however it can also be used in tracking changes in any files. Git also one if the most widely used VCS in developer world. Git is a mature, actively maintained open source project originally developed in 2005 by Linus Torvalds, the famous creator of the Linux operating system kernel. A staggering number of software projects rely on Git for version control, including commercial projects as well as open source. Developers who have worked with Git are well represented in the pool of available software development talent and it works well on a wide range of operating systems and IDEs (Integrated Development Environments). Git has the functionality, performance, security and flexibility that most teams and individual developers need. These attributes of Git are detailed above. In side-by-side comparisons with most other alternatives, many teams find that Git is very favorable.
Git as Open Source Project
Git is a very well supported open source project with over a decade of solid stewardship. The project maintainers have shown balanced judgment and a mature approach to meeting the long term needs of its users with regular releases that improve usability and functionality. The quality of the open source software is easily scrutinized and countless businesses rely heavily on that quality. Being open source lowers the cost for hobbyist developers as they can use Git without paying a fee. For use in open-source projects, Git is undoubtedly the successor to the previous generations of successful open source version control systems, SVN and CVS.
3. Change the current working directory to the location where you want the cloned directory to be made. Type
4. Enter. Your local clone will be created.
How to clone a git repository using CMD?
1. Install Git Bash in your pc.
2. Open Git Bash.
git clone
, and then paste the URL you copied in Step 2.git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
4. Enter. Your local clone will be created.
git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY Cloning into `Spoon-Knife`... remote: Counting objects: 10, done. remote: Compressing objects: 100% (8/8), done. remove: Total 10 (delta 1), reused 10 (delta 1) Unpacking objects: 100% (10/10), done.
Open System (Open API) & Open Source
Open Platform (API)
An Open API (often referred to as a Public API) is a publicly available application programming interface that provides developers with programmatic access to a proprietary software application. APIs are sets of requirements that govern how one application can communicate and interact with another. They also allow developers to access certain internal functions of a program. In the simplest terms, an API allows one piece of software to interact with another piece of software. They may be used by both developers inside the organization that published the API or by any developers outside that organisation who wish to register for access to the interface.
Open API vs Open Source
An open API is one that is openly an freely available for anyone to use. Open APIs make a lot of sense on the web, where an open web API can be used to let third party software developers integrate pieces of your web site into theirs. While, the core idea behind open source is to give away the source code to your software so that anyone can study, fix and improve it. This tends to produce better software and happier developers and customers. However, the idea of open source goes against decades of software distribution business models that are based on keeping source code private and selling you software that you can’t modify.
Below is another reference and well explained about what an Open API means
Keywords :
Open Source - decentralized software development
Open Api - decentralized business development
Tuesday, 21 February 2017
Topic 3 - Eloquent ORM & Relationship
Introduction
Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.
First off u need to declare namespace inside php file and extend eloquent package.
<?php namespace App; use Illuminate\Database\Eloquent\Model;
Then, you can list out key working elements and define them in Eloquent ORM
- primary key
- table name
- mass assignments
Primary Keys
In Eloquent ORM , each model class will assume the tables has default primary key which namely id . You can override primary key inside model class using $primaryKey attribute.
class Customer extends model{ protected $primaryKey = 'customer_id'; }
Table Naming
Basically laravel will use default naming for tables if user did not specific the table name, such that using plural name for the model class. In this case, the class we are using is Customer. Turn out laravel will assume model record in customers table. You can specific table name by define using $table key.
class Customer extends model{ protected $table = 'customer'; }
Mass Assignment
You can define model attributes and make mass assignable. Use the $fillable key to make assign array elements.
class Customer extends model{ protected $fillable = array('customerid','customername'); }
Eloquent Relationship
Activities
1. Create Model Class (Customer, Customer Contact)
2. Modify App/Routes/Web.php
3. Create View Class using Blade Templating Engine
4. Create Eloquent Relationship
Sample Application
Today's lesson are creating model class that will create a relationship between two tables to produce a valuable information such that to create bills to customers or to get contact information based on their primary id.
Example of Creating Model Class (Customer)
class Customer extends model { protected $table = 'customer'; protected $fillable = array('customerid','customername'; public function customer_contact() { return $this->hasMany('App\Customer_contact); } }
References
https://laracasts.com/discuss/channels/eloquent/laravel-table-names-are-plural-by-default
https://laravel.com/docs/5.4/eloquent
Topic (Laravel) 2 - Routing and Configuring Database
Basic Routing
Previous lesson we have learn installing Laravel Framework via composer in Windows OS. Basically the first thing when you open a localhost website laravel is that you will notice the "route" thing on website URL.Such that http://localhost/laraveltest/public/ will direct us to welcome page stated in our route.php. Eloquent 5.x changes route.php inside routes directory located at routes\web.php.
Example of source code that direct welcome page by returning view model named welcome.php.
Route::get('/', function () {
return view('welcome');
});
Route Parameters
Eventually Laravel Framework provide a future that enables view of specific segment divide according to each object. Such as to distinct or finding exclusive customer we can pass the parameter using 'customer/{id}' .
Route::get('customer/{id}', function ($id) {
return 'Customer'.$id;
});
Database Configuration
The database of your laravel project is located at config/database.php. By default laravel will use mysql as default database connection and connect to localhost server.
'default' => env('DB_CONNECTION', 'mysql'),
However you can change specific connection on this file according to your remote host server.
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
'sslmode' => 'prefer',
],
],
That file (
config/database.php
) is the actual configuration file that will be used. That file just happens to pull some values from the env
. This allows you to not have to change the config files themselves when you have a project on different servers. You can just have a different .env
file on each host that specifies its unique values for those.
Imagine you are working with other people. They will have different configuration for their database. Having to hardcode values into the config file that is committed to a repository would end up with some problems as they pull down changes their configs might get overwritten. The
.env
file is not committed and should not be as its unique to the 'host'.
By having the config files pull values from
env
, each person (host) can have their own .env
file with their own values without having to make changes to the actual config files.References
https://laravel.com/docs/5.4/routing
https://laravel.io/forum/05-28-2016-env-file-vs-configdatabasephp
Monday, 20 February 2017
Topic (Laravel) 1 - Laravel Framework Installation
Below are steps instruction for someone to get started with Laravel framework hence using it in day-to-day business operation in development environment.
Step 1 - Download composer and install it on your computer.
Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. You can get composer from here.
Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. You can get composer from here.
Step 2 - Install Laravel
You can install Laravel by issuing the Composer create-project command in your terminal. But before that, you need to make sure the directory of your project must install according to intended directory.
For this example we change directory in cmd to www folder inside wamp server
cd c:\wamp64\www
Then, you can write down :
composer create-project laravel/laravel laraveltest
The composer will create the laravel project folder for you. Installation may require several minutes. You may find the created folder in this directory :
cd c:\wamp64\www\laraveltest
Step 3 - Open Laravel using Localhost
After installation is success, you may open front page by typing on website address.
http://localhost/laraveltest/public/
OR
you can serve up the local host using artisan command and then open our website using command line http://localhost:8000/
php artisan serve
http://localhost:8000/
If after git clone , you may need to do these:
1. composer dump-autoload
2. composer install
3. php artisan key:generate
References
https://laravel.com/docs/5.4
https://www.tutorialspoint.com/laravel/laravel_installation.htm
Outline - Laravel Lesson
The PHP Framework For Web Artisans
Outline lesson
- Able to install laravel framework in windows Operating System.
- Learn to understand basic routing to make a route request to an appropriate controller.
- Learn to understand database configuration inside laravel.
- Learn to use model class using Eloquent ORM.
- Able to elaborate open system and open source program.
- Learn to use templating engine such as blade template.
Subscribe to:
Posts (Atom)