Nasrul Hazim Bin Mohamad

4 Essential Laravel Packages for Your Web Application Development

Dec
20

Assalamualaikum,

Recently I’ve been working with developing Laravel packages for my own use and Laravel’s community. It’s quite fun and interesting how you can separate the modules or features from Laravel’s main application and make it as a package, which later on you can reuse it over and over again.

Here are some of the packages I’ve created so far. You may want to try it out, and please do make a report if there’s any issues.

  1. Artisan Extended – this package mainly to add more artisan commands to simplify and speed up your development progress. Here the list of commands available:
    1. clear:cache – Put application under maintenance, clear common caches files, and put the application up again
    2. clear:serve – Run clear:cache and serve the application
    3. make:route – Create a new route
    4. make:view – Create a new plain view or resourceful view
    5. make:resourceful – Create a new resourceful controller
    6. make:scaffold – Create a new model, migration, resourceful controller and views (but still, need to enhance to accept columns details)
    7. secure:cookie – Secure your cookie
  2. Themer – The package main purpose to support theming in Laravel’s applications. It’s provide a middleware, and an artisan command(make:theme) to create a new theme.
  3. Setting – A simple helper to have a setting for your application.
  4. Subscriptions – The package is used for SaaS based applications. It’s allow you to add new package services, and enable your customers to subscribe to your SaaS application.
Sample Subscription Implementation in SaaS Application

Sample Subscription Implementation in SaaS Application

Do play around with the packages, and do report issues if there’s any, or if you think there’s need enhancement, do submit your proposal.

Laravel: Managing Routes

Dec
13

Assalamualaikum,

Recently I’ve meet some of my friends, and clients working with Laravel projects. It’s seems that, Route, managing routes is quiet painful when your application become bigger and you have to handle a lots of routes.

So, what’s come out of my mind was, how to manage Laravel’s routes more efficient?

I’ve come up with few possible options:

  1. Define more map methods in RouteServiceProvider, and call them – but this will make the RouteServiceProvider full with map methods, which I don’t prefer it that way – to many mapping routes method.
  2. Then I’ve come up with ideas having route trait, then you just need to attach it to any classes which you prefer, then call it any RouteServiceProvider or in routes/web.php. But having trait just to manage the routes, it’s like overkill (up till now), so I skip creating the trait.
  3. Then I’ve come up with having another route folder, purposely to serve the routes – I’ve named it Routes, in app directory. In the Routes directory, you create a class,  and have a method routes. In that method you just need to define your route – but of course, you need to import Route facade. Below is an example of implementation.

Now you should have much cleaner codes in your routes/web.php. You just need to include the route namespace, and call the className::routes() to load the routes.

That will be much cleaner routes. You may want to structure your app/Routes directory to support route’s version, or prefix, etc.

Hopes the idea will help out developers to easily manage their projects.

Hope the approach won’t break the incoming Laravel releases! ^_^

I think that’s what I want to share for now. Thanks for reading!

System Development: Must Have 3rd Party Library

Dec
22

A list of useful libraries used for system development – such as uploading, sorting, beautiful alert messages.

So, you don’t have to stick to those old schools methods for all the above. 🙂

ply

Ply, beautiful alert messages and even you can customize for login or registration modal.

DropzoneJS, similar to WordPress uploading Media.

DropzoneJS, similar to WordPress uploading Media.

sortable

Sortable, useful when it’s come to sort out your staff list for instance, or probably you have a list of products need to be sort.

Website Development – Front-end

Dec
20

I’ve been working recently on what’s the basic / features used in most websites in 2015. Here is the list:

  1. Parallax
  2. Carousel
  3. Animate
  4. Smooth Scrolling
  5. Flat UI Design
  6. Nice & Clean Icons
  7. UI Framework
  8. JavaScript Library with their extensions
  9. Slider

From all of features above can be achieve by using following plugins/extension/library:

  1. Carousel – Owl Carousel
  2. Parallax – Parallax.js
  3. Animate – Animate.css
  4. Smooth Scroll – see my post here
  5. Fontello – include Font Awesome, Fontellico, etc.
  6. Ui Framework – Bootstrap, Foundation
  7. Slider – Light Slider

In 2016, I think most of the above still remain use.

A bit of reading just now – probably my next project will use Angular Material.

Y2016

Dec
18

Year 2016, InsyaAllah, next year to be a year of sharing knowledge of what I’ve learnt so far. Following are the trainings I would like to conduct:

1. Mobile Apps Development with jQuery Mobile
2. Mobile Apps Development with Intel XDK (incoming)
3. API Development with Slim Framework (incoming)
4. PHP Basic / Advanced
5. Web Development with CakePHP 3 (incoming)
6. Web Development with Laravel 5 (incoming)
7. Web Development with Yii Framework 2 (incoming)
8. WordPress for Developers – Beginner Level
9. WordPress Theme Development
10. WordPress Plugin Development

Those status incoming, it’s the one I’m preparing the syllabus & materials, summarizing the process, and so on. Hope more things can be share other than mentioned above such as the tools I’ve used along the process of the development – Sublime Text 3, SQLYog, Putty, Git and so on

Training: Web Mobile Application Development (Basic / Intermediate) – INTIM – August 2015

Aug
16

Training: Web Mobile Application Development (Basic / Intermediate)

Location: INTAN Kampus Wilayah Timur (INTIM), Kemaman, Terengganu

Date: 17th – 20th August 2015

Slide: http://bit.ly/training-web-mobile-application-development

Training Materials:

  1. Web Mobile Application Starter Kit – https://bit.ly/training-mobile-app-starter-kit
  2. Basic Android Configuration – https://bit.ly/training-mobile-app-android-config
  3. API Template – https://bit.ly/training-api-template

Important Articles:

  1. HTTP Methods for Restful Services – http://bit.ly/htpp-nethods-for-restful-services
  2. Android Configuration – http://bit.ly/android-config-xml
  3. Chrome Device Mode – http://bit.ly/chrome-device-mode

 

Web Services: Slim Framework + Eloquent(Laravel)

May
02

Setting up the Restful API is easy with Slim Framework & Eloquent(Laravel). Here are the steps:

  1. Install required components via composer – Slim Framework + Eloquent(Laravel)
  2. Create a database called web_services and create users table.
  3. Setting up Eloquent
  4. Setting up Routes
  5. Final Touch
Web Service Restful API

Web Service Restful API

Install the necessary components using composer – create a composer.json and save it in a working directory and run composer install.

{
    "name": "Web Services",    
    "require": {
        "php": ">=5.3.0",
        "slim/slim": "2.*",
        "slim/views": "0.1.*",
        "illuminate/database": "5.0.*",
        "illuminate/events": "5.0.*"
    },
    "autoload": {
        "classmap": [
            "models"
        ]
    }
}

We’re creating a simple web services for Users – Simple CRUD. Create a database called web_services and run the following SQL statement to create user table.

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Next, setting up the Eloquent. Create a database.php in config folder(Please create this folder in the working directory) folder.

$database = [
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'web_services',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
];

use IlluminateDatabaseCapsuleManager as Capsule;

$capsule = new Capsule;

$capsule->addConnection($database);

// Set the event dispatcher used by Eloquent models... (optional)
use IlluminateEventsDispatcher;
use IlluminateContainerContainer;
$capsule->setEventDispatcher(new Dispatcher(new Container));

// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();

Once we’re done with Eloquent, next we going to set up the routes for Users CRUD operations. Save your time, copy & paste the following codes and save it in config/routes.php.

<?php

$app->get('/api/users', function () {
    echo User::all()->toJson();
});

$app->get('/api/users/:id',  function($id) {
	try {
		echo User::find($id)->toJson();
	} catch (Exception $e) {
		echo '{"error":{"text":'. 'Unable to get the web service. ' . $e->getMessage() .'}}';
	}
});

$app->get('/api/users/search/:query', function($query) {
	echo User::where('name', '=', $query)->get()->toJson();
});

$app->post('/api/users/add', function() use ($app) {
    try {
        $user = new User;

        $user->name = $app->request()->post('name');
        $user->phone = $app->request()->post('phone');
        $user->email = $app->request()->post('email');

        if($user->save()) {
            echo '{"message":"Successfully add new user"}';
        } else {
             echo '{"message":"Failed to add new user"}';
        }
    } catch (Exception $e) {
        echo '{"error":{"text":'. 'Unable to get the web service. ' . $e->getMessage() .'}}';
    }

});

$app->put('/api/users/update/:id', function($id) use ($app) {
    try {
        $user = User::find($id);

        $user->name = $app->request()->post('name');
        $user->phone = $app->request()->post('phone');
        $user->email = $app->request()->post('email');

        if($user->save()) {
            echo '{"message":"Successfully update user info"}';
        } else {
             echo '{"message":"Failed update user info"}';
        }   
    } catch (Exception $e) {
        echo '{"error":{"text":'. 'Unable to get the web service. ' . $e->getMessage() .'}}';
    }
    
});

$app->delete('/api/users/:id', function($id) {
	$user = User::find($id);
	
    if($user->delete()) {
        echo '{"message":"Successfully delete user"}';
    } else {
         echo '{"message":"Failed to delete user"}';
    }
});

OK, here the final touch! 2 things to do, one the index.php and the other one is .htaccess. Here the index.php. Please take note, we require the header("Access-Control-Allow-Origin: *");, to ensured that we can access this Restful API from other domains. There might be security issues. Comments are welcomed.

<?php
try {
	header("Access-Control-Allow-Origin: *");
	require 'vendor/autoload.php';
	require 'config/database.php';
	require 'config/initialize.php';
} catch (Exception $e) {
	echo '{"error":{"text":'. 'Unable to start up the web service. ' . $e->getMessage() .'}}';
}

The .htaccess.

RewriteEngine On

# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Source code available at: Web Service(Restful API)

I Have 3 demo available:

  1. Web Service App
  2. Web Service Demo
  3. Web Service Mobile Demo

 

Micro-framework: Slim

Apr
22

Setting up Slim Application

  • Create a folder for your project, mine called slim
  • create a composer.json in the directory and open up your Command Prompt / Terminal and run composer install. Later you should have something similar to Screenshot #2.
    mf-composer

    Screenshot #1

    mf-structure

    Screenshot #2

Setting up RedBeanPHP4

  • Download RedbeanPHP4
  • Create a folder named RedBeanPHP4 in vendor directory and extract download zip file above and copy the rb.php into slim/vendor/RedBeanPHP4 – see Screenshot #2.
  • Include the rb.php in slim/vendor/autoloader.php
    mf-autoloader
  • Then, add MySQL connection settings.

Let’s start it!

  • Create a index.php in slim directory and add the following:
    mf-slimframeworkBasically what’s in this index.php is to add new user and view a user details.
  • You may need to create new database, then new table named users. I used the following fields – id, name, email, created and modified
  • Next, when the database and tables created, you may run http://localhost/slim/users/add/Nasrul Hazim/email@gmail.com and you may want to add more records. Suppose each time new user created, you will be redirected to the view user info page – http://localhost/slim/users/view/1 and see the next screenshot – I only var_dump the user details and you want to add some nice view or probably pass a JSON encoding.
    mf-db
    mf-readbean-orm


HTML5: Get Current Position

Sep
12
(function($) {
	 
    var methods = {
        current : function()
        {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(position, error);
            }

            function position(pos) {
                var latitude = pos.coords.latitude;
                var longitude = pos.coords.longitude;

                alert('Latitude: ' + latitude + ', Longitude: ' + longitude);
            }

            function error(err) {
                alert('ERROR(' + err.code + '): ' + err.message);
            };
        },
    };
     
    $.fn.Location = function(method) {
        if (methods[method])
        {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof method === 'object' || !method)
        {
            return methods.init.apply(this, arguments);
        }
        else
        {
            $.error('Method ' + method + ' does not exist on jQuery.Ika');
        }
    };
     
})(jQuery);

$(document).ready(function(){
    $(document).Location('current');
});

Refererences:

  1. https://developer.mozilla.org/en-US/docs/Web/API/Geolocation.getCurrentPosition
  2. http://dev.w3.org/geo/api/spec-source.html

Python: Setting up in Windows 7

May
01
Python

Python

  1. Download latest 2.x at https://www.python.org/downloads/
  2. Set Environment path: C:Python27;C:Python27Libsite-packages;C:Python27Scripts;
  3. Install Setuptools: https://pypi.python.org/pypi/setuptools#windows-7-or-graphical-install
    1. Download the script
    2. Open CMD
    3. Go to the script directory
    4. Run the script: python ez_setup.py
    5. Exit once done (Ctrl + Z, then Enter)

Test your installation by open up CMD, and type in python. You should see something similar to the screen shot below.

cmd-python

Following are optional:

  1. Install pip: C:> easy_install pip
  2. Install the followng using pip
    1. Mechanize: C:> pip install mechanize
    2. BeatifulSoup4: C:> pip install beautifulsoup4
    3. CSVKIT: C:> pip install csvkit

References:

  1. http://www.anthonydebarros.com/2011/10/15/setting-up-python-in-windows-7/
  2. http://www.anthonydebarros.com/2011/09/11/csvkit-data-files/