Slim Framework

From XennisWiki
Jump to: navigation, search

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. (Slim Framework)

REST API example with Idiorm and MySQL

index.php

<?php

require 'libs/Slim/Slim.php';
require 'libs/idiorm/idiorm.php';

ORM::configure(array(
    'connection_string' => 'mysql:host=HOST;dbname=DB-NAME',
    'username' => 'USER',
    'password' => 'PASSWORD'
));

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->hook("slim.before.router", function() use ($app) {
	$path = $app->request()->getPathInfo();
	if (strpos($path, "article") !== false) {
		require 'entities/article.php';
	}
});

$app->get('/article', function() { getArticles(); });
$app->get('/article/:id', function($id) { getArticle($id); });

$app->run();

entities/article.php

<?php

function getArticles() {
	$articles = ORM::for_table('article')->order_by_asc('name')->find_many();
	if (!empty($news)) {
		$result_arr = Array();
		foreach ($articles as $item) {
			array_push($result_arr, $item->as_array());
		}
	} //else {
//		$result_arr = array('status' => 'error', 'msg' => 'no news found');
//	}
	echo json_encode($result_arr);
}

function getArticle($id) {
	$item = ORM::for_table('article')->where_id_is($id)->find_one();		
	echo json_encode($item->as_array());
}

Rewrite engine

Further information: Rewrite engine

.htaccess

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

See also

External links