Nasrul Hazim Bin Mohamad

Quick Development: Slim Framework + Illuminate(Laravel)

Apr
27

Create a project folder and add a composer.json file in it and paste the following codes, and run composer install. You should have Slim Framework, Twig, Illuminate(Laravel) in the project folder.

{
    "name": "Quick Dev!",
    "require": {
        "php": ">=5.3.0",
        "slim/slim": "2.*",
        "slim/extras": "2.*",
        "twig/twig": "1.*",
        "illuminate/database": "*"
    },
    "autoload": {
        "classmap": [
            "models"
        ]
    }
}

Add a index.php file in project folder and copy paste the following:

<?php

require 'vendor/autoload.php';

// Database information
$settings = array(
    'driver' => 'mysql',
    'host' => '127.0.0.1',
    'database' => 'dbname',
    'username' => 'username',
    'password' => 'password',
    'collation' => 'utf8_general_ci',
    'prefix' => '',
    'charset' => 'utf8'
);

// Bootstrap Eloquent ORM
$container = new IlluminateContainerContainer;
$connFactory = new IlluminateDatabaseConnectorsConnectionFactory($container);
$conn = $connFactory->make($settings);
$resolver = new IlluminateDatabaseConnectionResolver();
$resolver->addConnection('default', $conn);
$resolver->setDefaultConnection('default');
IlluminateDatabaseEloquentModel::setConnectionResolver($resolver);

$app = new SlimSlim();

$app->get('/', function () {
    echo "<h1>Quick Dev!!</h1>";
    $articles = Article::all();
    echo $articles->toJson();
});

$app->run();

Create a folder named models in the project folder and add the following into a file named Article.php:

<?php

class Article extends IlluminateDatabaseEloquentModel
{

}

Don’t forget our .htaccess file in a project folder. 🙂

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

Now you can navigate to your system, for example: http://localhost/quick-dev

p/s: You can use Twig later on. 🙂

Reference: http://revul.es/slim/#/60

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


Phalcon: First Time Setup (for Windows & WAMP)

Mar
23

Download Phalcon’s .dll file based on your environment – i’m using WampServer 32 bit(check with Task Manager if you don’t know your WampServer running on 32 bit or 64 bit).

Once downloaded, extract the php_phalcon.dll into C:wampbinphpphp[version]ext.

Add extension=php_phalcon.dll in 2 places:

  1. C:wampbinapacheapache[version]binphp.ini
  2. C:wampbinphpphp[version]php.ini

Now, restart your WampServer services and check phpinfo(), see if it’s loaded or not.

p/s: I used Phalcon’s .dll with no NTS, for PHP 5.5, and for 32 bit.

Phalcon: Multiple-Module Skeleton

Mar
20

Assalamualaikum,

I’ve been learning Phalcon Framework recently and end up built a Multiple-Module Skeleton app – basically to ease development process to manage modules. Looking forward to add in more features. I have it on GitHub.

I have the directory structure as follow:

Phalcon - Multi Modules Structure - NHM - 1.0 - 20150313

Phalcon – Multi Modules Structure – NHM – 1.0 – 20150313

Hope to get some feedbacks.

Jazakumullahu khairan.

DomPDF: Production Ready Configuration

Feb
17

DomPDF – Production Ready Configuration

PHP 

  • Version: 5.3 and above
  • Settings: allow_url_fopen
  • Extensions: MBString (Installation), GD (Installation), DOM(enabled by default)

DomPDF Configuration / Usage

  • Enable Remote – def("DOMPDF_ENABLE_REMOTE", true);
  • Read/Write access to the DOMPDF_TEMP_DIR
  • Use Absolute URL
  • Use Full Document Root or Relative (if you’re still unable to view the image)
  • Use JPEG

UPDATE (2015-02-17): Security Issues on allow_url_fopen or Is allow_url_fopen safe?

Training – PHP & MySQL: Basic to Advanced

Jan
02

PHP: Generate Random Hex Color Code

Oct
14
&lt;?php

$colors = array();
for($i = 0; $i &lt; 10; $i++) {
	$color = $this-&gt;random_color();

	while(in_array($color, $colors)) {
		$color = $this-&gt;random_color();
	}

	$colors[] = $color;
}

foreach ($colors as $key =&gt; $value) {
	echo '&lt;span style=&quot;color:'.$value.'&quot;&gt;&lt;strong&gt;'.$value.'&lt;/strong&gt;&lt;/span&gt;&lt;br&gt;';
}

function random_color_part() {
		return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
}

function random_color() {
    return '#'. random_color_part() . random_color_part() . random_color_part();
}

?&gt;

Result:

random-hex-code

HTML: Editable Elements

Apr
24

I’m using the following:

  1. X-editable
  2. Bootstrap 2
  3. Cakephp / Any PHP Framework

Include the jQuery, Bootstrap 2 in your HTML head

&lt;head&gt;
    &lt;!-- jQuery --&gt;
    &lt;script src=&quot;//code.jquery.com/jquery-1.11.0.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;//code.jquery.com/jquery-migrate-1.2.1.min.js&quot;&gt;&lt;/script&gt;

    &lt;!-- Bootstrap --&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;link href=&quot;css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; media=&quot;screen&quot;&gt;
    &lt;script src=&quot;js/bootstrap.min.js&quot;&gt;&lt;/script&gt;

    &lt;!-- X-Editable --&gt;
    &lt;link href=&quot;//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap-editable/css/bootstrap-editable.css&quot; rel=&quot;stylesheet&quot;/&gt;
    &lt;script src=&quot;//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap-editable/js/bootstrap-editable.min.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;

The View

&lt;a href=&quot;#&quot; class=&quot;x-editable&quot; data-type=&quot;text&quot; data-pk=&quot;1&quot;&gt;Some value 1&lt;/a&gt;
&lt;a href=&quot;#&quot; class=&quot;x-editable&quot; data-type=&quot;text&quot; data-pk=&quot;2&quot;&gt;Some value 2&lt;/a&gt;

The JavaScript

$(document).ready(function() {
    $.fn.editable.defaults.mode = 'inline';

    $('.x-editable').editable({
        url: 'something/update'
    });
});

The Controller

&lt;?php 
App::uses('AppController', 'Controller');

class Something extends AppController {

    public function update()
    {
        /* Data structure we received from x-editable
            Array
            (
                [name] =&gt; 
                [value] =&gt; Some value 1
                [pk] =&gt; 1
            )
        */
        $data = $this-&gt;request-&gt;data;
        $this-&gt;Some-&gt;read(null, $data['pk']);
        $this-&gt;Some-&gt;set('value', $data['value']);
        $this-&gt;Some-&gt;save();
        // return JSON if u need it or render a HTML (need to handle on success event)
    }
}
?&gt;

References

  1. X-editable
  2. http://jquery.com/download/
  3. http://getbootstrap.com/2.3.2/getting-started.html

Angular X-editable – http://vitalets.github.io/angular-xeditable

Kohana – Tips on Setting up Routes

Jun
04

Always set the default Route the last one, else specific Route will be overwritten

Set specific Route for a particular task

// specific Route for a particular task 
Route::set('doSomething', 'doSomething(/&lt;controller&gt;(/&lt;action&gt;(/&lt;id&gt;)))')
    -&gt;defaults(
		array(
			'directory'  =&gt; 'doSomething',
			'controller' =&gt; 'page',
			'action'     =&gt; 'index',
		)
	);
	
// set default at the last position, else other routes will not work
Route::set('default', '(&lt;controller&gt;(/&lt;action&gt;(/&lt;id&gt;)))')
    -&gt;defaults(
		array(
			'directory'  =&gt; '',
			'controller' =&gt; 'page',
			'action'     =&gt; 'index',
		)
	);

GeoServer – GetFeatureInfo Template Data Model (structure)

Mar
21

Extend from this GeoServer – Custom Get Feature Info Display

Knowledge requirement – Freemaker

The standard template files is header.tpl, content.tpl, footer.tpl.

header.tpl usually where JavaScript, CSS, meta tag, title placed here.

footer.tpl where you put your HTML page footer, Copyright, etc.

content.tpl where we going to iterate through all the features to display interactive UI. But here, I’m going to explain the structure of all available variables.

/**
features (array of Feature)
	[0]
		- fid
		- typeName
		- attributes
			-&gt; name
			-&gt; type
			-&gt; isGeometry
			-&gt; value
		- type
			-&gt; name
			-&gt; title
			-&gt; abstract
			-&gt; description
			-&gt; keywords
			-&gt; metadataLinks
			-&gt; SRS
			-&gt; nativeCRS
	[n]
	
type (object of Feature Map)
	- name
	- attributes
		-&gt; name
		-&gt; type
		-&gt; isGeometry
**/

Accessing the variables as following:

&lt;!-- Accessing Feature Type Name --&gt;
&lt;h3&gt;${type.name}&lt;/h3&gt;

&lt;!-- Accessing Features at index 0 and assign to a variable named feature --&gt;
&lt;#assign feature = features[0]&gt;

&lt;!-- Get feature's attributes values and assign to a variable named attrs --&gt;
&lt;#assign attrs = feature.attributes&gt;

&lt;!-- Display an attribute --&gt;
&lt;p&gt;${attr.someFieldName.value}&lt;/p&gt;

The result may display as below:

This is type name

some field name value

Reference: http://docs.geoserver.org/2.1.4/user/tutorials/freemarker.html