Category Archives: php

Using Laravel with Resource Controllers and Method Filters

Using filters on routes in routes.php is as simple as:

Route::get('/something/{smth}', array('before' => 'auth', function($smth) {
     return "There is something called {$smth} ";
 }));

When using controllers filters may be specified like this:

Route::get('profile', array('before' => 'auth',
            'uses' => 'UserController@showProfile'));

However if you used to use Resource controllers like this:

Route::resource('something', 'SmthController');

Then an option is to specify filters from within your controller like this:

public function __construct()
{
    $this->beforeFilter('auth', array('only' =>
                    array('store', 'update', 'destroy')));
}

This however will not be so transparent to someone not knowing your code, so another good option is to declare a group Route in routes.php and put all secure routes there probably handled by different controllers and methods:

// secure routes
Route::group(array('before' => 'auth'), function()
{

    Route::resource('something', 'SmthController');

    Route::get('smthspecial', 'SmthController@get_smth_special');
    Route::any('search/(:all?)', 'SearchSmth@index');

    Route::controller(array(
        'dashboard',
        'messages',
        'friends',
        'admin.dashboard',
        'admin.users',
    ));

    Route::any('edit_profile', 'profile@edit');
    Route::get('(:any)', 'profile@view');
});

 

PHP REST API Frameworks

What is the best PHP REST API Framework?

There are plenty of different projects out there which suits different needs.

Here is a list of some most popular and actively developed PHP REST API frameworks.

Note some may be not really RESTful.

Epiphany

The Epiphany framework is fast, easy, clean and RESTful. The framework does not do a lot of magic under the hood. It is, by design, very simple and very powerful.

The documentation provides a few conventions that we believe lead to well written code but you’re free to use any style you’d like. The framework never dictates how you should write or structure your application.

https://github.com/jmathai/epiphany

Fat Free

A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust web applications – fast!

  • Super lightweight code base with just ~55kb
  • Full-featured toolkit
  • Easy to learn, use and extend
  • Fast and clean template engine
  • Unit testing toolkit
  • Database-managed sessions
  • Markdown-to-HTML converter
  • Atom/RSS feed reader
  • Image processor
  • Geodata handler
  • On-the-fly Javascript/CSS compressor
  • OpenID (consumer)
  • Custom logger
  • Basket/Shopping cart
  • Pingback server/consumer
  • Unicode-aware string functions
  • SMTP over SSL/TLS
  • Tools for communicating with other servers
  • Data Validation
  • and more Plugins from the F3-Community

http://fatfreeframework.com

Flight

Flight is a fast, simple, extensible framework for PHP. Flight enables you to quickly and easily build RESTful web applications.

http://flightphp.com

Frapi

Frapi is a  high-level PHP REST API framework that powers web apps, mobiles services and legacy systems, enabling a focus on business logic and not the presentation layer.
FRAPI handles multiple media types, response codes and generating API documentation. It was originally built by echolibre to support the needs of their client’s web apps, and now it’s been open-sourced.

http://getfrapi.com/

Guzzle

Guzzle takes the pain out of sending HTTP requests and the redundancy out of creating web service clients. It’s a framework that includes the tools needed to create a robust web service client, including: Service descriptions for defining the inputs and outputs of an API, resource iterators for traversing paginated resources, batching for sending a large number of requests as efficiently as possible.

  • All the power of cURL with a simple interface.
  • Persistent connections and parallel requests.
  • Streams request and response bodies.
  • Service descriptions for quickly building clients.
  • Powered by the Symfony2 EventDispatcher.
  • Use all of the code or only specific components.
  • Plugins for caching, logging, OAuth, mocks, and more.
  • Includes a custom node.js webserver to test your clients.

http://guzzlephp.org

Kohana

An elegant HMVC PHP5 framework that provides a rich set of components for building web applications.

  • Many common components are included: translation tools, database access, code profiling, encryption, validation, and more.
  • Use specific libraries and tools: extending existing components and adding new libraries is very easy.
  • Write commercial applications: uses the BSD license, so you can use and modify it for commercial purposes.
  • A very fast framework: benchmarking a framework is hard and rarely reflects the real world, but Kohana is very efficient and carefully optimized for real world usage.
  • Good debugging and profiling tools: simple and effective tools help identify and solve performance issues quickly.
  • Know what the framework is doing: very well commented code and a simple routing structure makes it easy to understand what is happening.
  • Work with objects and classes: an OOP framework that is extremely DRY. Everything is built using strict PHP 5 classes and objects.
  • Write your own code: there are no code generators and endless configuration files, so setting up is fast and easy.
  • Community support: a very active community forum and IRC channel means that most questions are answered very quickly.

http://kohanaframework.org

Laravel

Laravel is a clean and classy framework for PHP web development. Freeing you from spaghetti code, Laravel helps you create wonderful applications using simple, expressive syntax. Development should be a creative experience that you enjoy, not something that is painful. A well written documentation is a big plus.

Advantages over other frameworks:

  • Bundles
  • The Eloquent ORM
  • Application Logic
  • Reverse Routing
  • Restful Controllers
  • Class Auto Loading
  • View Composer
  • The Inversion of Control (IoC) container
  • Migrations
  • Unit-Testing
  • Automatic Pagination

http://laravel.com

Recess

You should enjoy PHP development. That’s why Recess exists. Recess is a RESTful PHP framework designed to give you a delightful development experience.

  • Tools included for every developer
  • Declarative PHP with annotations
  • Stays out of your way, not in it
  • Loosely coupled Model-View-Controller
  • Create RESTful APIs with Ease
  • D.R.Y. in philosophy & practice
  • Caching-oriented architecture
  • Open source under MIT license

http://www.recessframework.org

Restler

A RESTful API server framework that is written in PHP that aids your mobile / web / desktop applications. A framework, but with a difference – Restler is all here to bend and mend to your needs. Turn your classes and its methods into an easily usable and better Web citizen with Restler.

  • Writing Server is made easy and light with just 3 PHP files
  • Simplicity through writing object oriented PHP like
  • Public methods are automatically mapped to a URL
  • Customization options and plugin architecture
  • Supporting for different formats like json, xml, yaml, amf, plist and custom formats
  • Support for different authentication schemes allowing to add your own auth plugins

http://luracast.com/products/restler

Slim

Slim is a lightweight PHP micro framework for simple yet powerful web applications and APIs.

  • Powerful router
    • Standard and custom HTTP methods
    • Route parameters with wildcards and conditions
    • Route redirect, halt, and pass
    • Route middleware
  • Template rendering with custom views
  • Flash messages
  • Secure cookies with AES-256 encryption
  • HTTP caching
  • Logging with custom log writers
  • Error handling and debugging
  • Middleware and hook architecture
  • Simple configuration

http://www.slimframework.com

Symfony2: FOSRestBundle

This bundle provides various tools to rapidly develop RESTful API’s & applications with Symfony2. Features include:

  • A View layer to enable output and format agnostic Controllers
  • A custom route loader to generate url’s following REST conventions
  • Accept header format negotiation including handling for custom mime types
  • RESTful decoding of HTTP request body and Accept headers
  • Exception controller for sending appropriate HTTP status codes

https://github.com/FriendsOfSymfony/FOSRestBundle

Symfony2: Silex

Silex is a PHP microframework for PHP 5.3. It is built on the shoulders of Symfony2 and Pimple and also inspired by sinatra.

A microframework provides the guts for building simple single-file apps. Silex aims to be:

  • Concise: Silex exposes an intuitive and concise API that is fun to use.
  • Extensible: Silex has an extension system based around the Pimple micro service-container that makes it even easier to tie in third party libraries.
  • Testable: Silex uses Symfony2′s HttpKernel which abstracts request and response making it very easy to test apps & the framework itself.
  • Respects the HTTP specification and encourages its proper use.

http://silex.sensiolabs.org

Tonic

A resource focused PHP RESTful API library where everything useful is a resource located by URLs.

  • URI annotations
  • Content negotiation
  • Method conditions
  • Mount points

http://peej.github.io/tonic

Wave Framework

A compact PHP micro-framework built loosely on model-view-control (MVC) architecture and factory method design pattern. It is made for web services, websites, info-systems and is built around a native API architecture, caching and smart image and resource management. Wave is a framework that does not include optional libraries with a very small footprint, lightweight and speed in mind.

Wave comes by default with a view controller and a gateway intended for website functionality with clean URLs that also incorporates a front-end JavaScript controller.

  • Modern API-centric framework for PHP versions 5.3 and above
  • Secure API requests with hash validation, token and key-based authentication
  • Dynamically loaded Hierarchical MVC objects through Factory pattern
  • API returns XML, CSV, JSON, HTML, native PHP and other data formats
  • Compressed data output with Deflate and Gzip
  • Input and output data is fully UTF-8
  • PDO-specific database controller for general-use database connections
  • Index gateway and Handlers for all types of HTTP requests
  • Caching system with tagging support for all types of dynamic and static requests
  • View and URL Controllers that support multiple languages and clean URL’s
  • Users and permissions control
  • jQuery JavaScript framework supported
  • On-demand dynamic image resizer and editor
  • On-demand resource compression, unifying and minifying
  • Automatic sitemap.xml and robots.txt generation
  • Automatically generated API documentation
  • API wrapper classes that make browser and server to server communication easy
  • 256bit Rijndael encrypted data transmission
  • API Observers for creating event-specific listeners
  • Installation-specific MVC class and resource overrides
  • Custom on-demand session handling
  • Request limiter that can block HTTP requests under certain conditions
  • Request logger that can be used for detailed performance grading of HTTP requests
  • Debugging, backup, update and filesystem maintenance tools
  • Compatibility script that tests support for server setup
  • Supports Apache and Nginx servers in Linux and Windows environments
  • Test Suite for API Testing
  • Filesystem caching, database cache, APC and Memcache supported
  • 100+ pages of detailed documentation and tutorials
  • Licensed under GNU Lesser General Public License Version 3

http://www.waveframework.com

Yii

Yii is a high-performance PHP framework best for developing Web 2.0 applications. It comes with rich features: MVC, DAO/ActiveRecord, I18N/L10N, caching, authentication and role-based access control, scaffolding, testing, etc. It can reduce your development time significantly.

http://www.yiiframework.com/

Zend: Zend_Rest_Server

Zend Framework 2 is an open source framework for developing web applications and services using PHP 5.3+. Zend Framework 2 uses 100% object-oriented code and utilises most of the new features of PHP 5.3, namely namespaces, late static binding, lambda functions and closures…

http://framework.zend.com

Simple php xml-rpc client to wordpress

Quick example how to get categories:

<?php
        require("class-IXR.php");  
        $client = new IXR_Client('http://myblog.com/xmlrpc.php');

        $USER = 'admin';
        $PASS = 'mypassword';

        if (!$client->query('wp.getCategories','', $USER,$PASS))
        {  
            echo('Error occured during category request.' . $client->getErrorCode().":".$client->getErrorMessage());  
        }
        $cats = $client->getResponse();

        if(!empty($cats))
        {
            echo 'Categories:<br /><hr />';
            foreach($cats as $_cat) echo $_cat['categoryName']."<br />";
        }

?>

 adding a new post

<?php
        require("class-IXR.php");  
        $client = new IXR_Client('http://domain.com/xmlrpc.php');

        $USER = 'admin';
        $PASS = 'mypassword';

        $content['title'] = 'Test title '.mt_rand();
        $content['categories'] = array("NewCategory","Nothing");
        $content['description'] = '<p>Lorem ipsum dolor sit amet</p>';
        $content['custom_fields'] = array( array('key' => 'my_custom_fied','value'=>'yes') );
        $content['mt_keywords'] = array('foo','bar');

        if (!$client->query('metaWeblog.newPost','', $USER,$PASS, $content, true))
        {
            die( 'Error while creating a new post' . $client->getErrorCode() ." : ". $client->getErrorMessage());  
        }
        $ID =  $client->getResponse();

        if($ID)
        {
            echo 'Post published with ID:#'.$ID;
        }

?>

XML-RPC Api specs: http://codex.wordpress.org/XML-RPC_WordPress_API

Full list of method calls as declared in the code: Continue reading