Flight - An Extensible Micro-framework for PHP2

  • Published on
    29-Dec-2015

  • View
    40

  • Download
    0

Embed Size (px)

DESCRIPTION

tentang mikro framerok

Transcript

<ul><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 1/13</p><p>FlightAn extensible micro-framework for PHP</p><p>about install learn code</p><p>User Guide</p><p>Routing</p><p>Extending</p><p>Overriding</p><p>Filtering</p><p>Variables</p><p>Views</p><p>Error Handling</p><p>Redirects</p><p>Requests</p><p>HTTP Caching</p><p>JSON</p><p>Configuration</p><p>Framework Methods</p><p>Routing</p><p>Routing in Flight is done by matching a URL pattern with a callback function.</p><p>Flight::route('/', function(){ echo 'hello world!';});</p><p>The callback can be any object that is callable. So you can use a regular function:</p><p>function hello(){ echo 'hello world!';}</p><p>Flight::route('/', 'hello');</p><p>Or a class method:</p><p>class Greeting { public static function hello() { echo 'hello world!'; }}</p></li><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 2/13</p><p>Flight::route('/', array('Greeting','hello'));</p><p>Routes are matched in the order they are defined. The first route to match a request will be invoked.</p><p>Method Routing</p><p>By default, route patterns are matched against all request methods. You can respond to specific methods</p><p>by placing an identifier before the URL.</p><p>Flight::route('GET /', function(){ echo 'I received a GET request.';});</p><p>Flight::route('POST /', function(){ echo 'I received a POST request.';});</p><p>You can also map multiple methods to a single callback by using a | delimiter:</p><p>Flight::route('GET|POST /', function(){ echo 'I received either a GET or a POST request.';});</p><p>Regular Expressions</p><p>You can use regular expressions in your routes:</p><p>Flight::route('/user/[0-9]+', function(){ // This will match /user/1234});</p><p>Named Parameters</p><p>You can specify named parameters in your routes which will be passed along to your callback function.</p><p>Flight::route('/@name/@id', function($name, $id){ echo "hello, $name ($id)!";});</p><p>You can also include regular expressions with your named parameters by using the : delimiter:</p><p>Flight::route('/@name/@id:[0-9]{3}', function($name, $id){ // This will match /bob/123 // But will not match /bob/12345});</p><p>Optional Parameters</p><p>You can specify named parameters that are optional for matching by wrapping segments in parentheses.</p><p>Flight::route('/blog(/@year(/@month(/@day)))', function($year, $month, $day){ // This will match the following URLS: // /blog/2012/12/10</p></li><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 3/13</p><p> // /blog/2012/12 // /blog/2012 // /blog});</p><p>Any optional parameters that are not matched will be passed in as NULL.</p><p>Wildcards</p><p>Matching is only done on individual URL segments. If you want to match multiple segments you can use</p><p>the * wildcard.</p><p>Flight::route('/blog/*', function(){ // This will match /blog/2000/02/01});</p><p>To route all requests to a single callback, you can do:</p><p>Flight::route('*', function(){ // Do something});</p><p>Passing</p><p>You can pass execution on to the next matching route by returning true from your callback function.</p><p>Flight::route('/user/@name', function($name){ // Check some condition if ($name != "Bob") { // Continue to next route return true; }});</p><p>Flight::route('/user/*', function(){ // This will get called});</p><p>Extending</p><p>Flight is designed to be an extensible framework. The framework comes with a set of default methods</p><p>and components, but it allows you to map your own methods, register your own classes, or even override</p><p>existing classes and methods.</p><p>Mapping Methods</p><p>To map your own custom method, you use the map function:</p><p>// Map your methodFlight::map('hello', function($name){ echo "hello $name!";});</p><p>// Call your custom method</p></li><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 4/13</p><p>Flight::hello('Bob');</p><p>Registering Classes</p><p>To register your own class, you use the register function:</p><p>// Register your classFlight::register('user', 'User');</p><p>// Get an instance of your class$user = Flight::user();</p><p>The register method also allows you to pass along parameters to your class constructor. So when you</p><p>load your custom class, it will come pre-initialized. You can define the constructor parameters by passing</p><p>in an additional array. Here's an example of loading a database connection:</p><p>// Register class with constructor parametersFlight::register('db', 'PDO', array('mysql:host=localhost;dnbname=test','user','pass'));</p><p>// Get an instance of your class// This will create an object with the defined parameters//// new PDO('mysql:host=localhost;dnbname=test','user','pass');//$db = Flight::db();</p><p>If you pass in an additional callback parameter, it will be executed immediately after class construction.</p><p>This allows you to perform any set up procedures for your new object. The callback function takes one</p><p>parameter, an instance of the new object.</p><p>// The callback will be passed the object that was constructedFlight::register('db', 'PDO', array('mysql:host=localhost;dnbname=test','user','pass'), function($db){ $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);});</p><p>By default, every time you load your class you will get a shared instance. To get a new instance of a class,</p><p>simply pass in false as a parameter:</p><p>// Shared instance of the class$shared = Flight::db();</p><p>// New instance of the class$new = Flight::db(false);</p><p>Keep in mind that mapped methods have precedence over registered classes. If you declare both using</p><p>the same name, only the mapped method will be invoked.</p><p>Overriding</p><p>Flight allows you to override its default functionality to suit your own needs, without having to modify any</p><p>code.</p><p>For example, when Flight cannot match a URL to a route, it invokes the notFound method which sends a</p></li><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 5/13</p><p>generic HTTP 404 response. You can override this behavior by using the map method:</p><p>Flight::map('notFound', function(){ // Display custom 404 page include 'errors/404.html';});</p><p>Flight also allows you to replace core components of the framework. For example you can replace the</p><p>default Router class with your own custom class:</p><p>// Register your custom classFlight::register('router', 'MyRouter');</p><p>// When Flight loads the Router instance, it will load your class$myrouter = Flight::router();</p><p>Framework methods like map and register however cannot be overridden. You will get an error if you try</p><p>to do so.</p><p>Filtering</p><p>Flight allows you to filter methods before and after they are called. There are no predefined hooks you</p><p>need to memorize. You can filter any of the default framework methods as well as any custom methods</p><p>that you've mapped.</p><p>A filter function looks like this:</p><p>function(&amp;$params, &amp;$output) { // Filter code}</p><p>Using the passed in variables you can manipulate the input parameters and/or the output.</p><p>You can have a filter run before a method by doing:</p><p>Flight::before('start', function(&amp;$params, &amp;$output){ // Do something});</p><p>You can have a filter run after a method by doing:</p><p>Flight::after('start', function(&amp;$params, &amp;$output){ // Do something});</p><p>You can add as many filters as you want to any method. They will be called in the order that they are</p><p>declared.</p><p>Here's an example of the filtering process:</p></li><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 6/13</p><p>// Map a custom methodFlight::map('hello', function($name){ return "Hello, $name!";});</p><p>// Add a before filterFlight::before('hello', function(&amp;$params, &amp;$output){ // Manipulate the parameter $params[0] = 'Fred';});</p><p>// Add an after filterFlight::after('hello', function(&amp;$params, &amp;$output){ // Manipulate the output $output .= " Have a nice day!";}</p><p>// Invoke the custom methodecho Flight::hello('Bob');</p><p>This should display:</p><p>Hello Fred! Have a nice day! </p><p>If you have defined multiple filters, you can break the chain by returning false in any of your filter</p><p>functions:</p><p>Flight::before('start', function(&amp;$params, &amp;$output){ echo 'one';});</p><p>Flight::before('start', function(&amp;$params, &amp;$output){ echo 'two';</p><p> // This will end the chain return false;});</p><p>// This will not get calledFlight::before('start', function(&amp;$params, &amp;$output){ echo 'three';});</p><p>Note, core methods such as map and register cannot be filtered because they are called directly and not</p><p>invoked dynamically.</p><p>Variables</p><p>Flight allows you to save variables so that they can be used anywhere in your application.</p><p>// Save your variableFlight::set('id', 123);</p><p>// Elsewhere in your application$id = Flight::get('id');</p><p>To see if a variable has been set you can do:</p></li><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 7/13</p><p>if (Flight::has('id')) { // Do something}</p><p>You can clear a variable by doing:</p><p>// Clears the id variableFlight::clear('id');</p><p>// Clears all variablesFlight::clear();</p><p>Flight also uses variables for configuration purposes.</p><p>Flight::set('flight.log_errors', true);</p><p>Views</p><p>Flight provides some basic templating functionality by default. To display a view template call the render</p><p>method with the name of the template file and optional template data:</p><p>Flight::render('hello.php', array('name' =&gt; 'Bob'));</p><p>The template data you pass in is automatically injected into the template and can be reference like a</p><p>local variable. Template files are simply PHP files. If the content of the hello.php template file is:</p><p>Hello, ''!</p><p>The output would be:</p><p>Hello, Bob!</p><p>You can also manually set view variables by using the set method:</p><p>Flight::view()-&gt;set('name', 'Bob');</p><p>The variable name is now available across all your views. So you can simply do:</p><p>Flight::render('hello');</p><p>Note that when specifying the name of the template in the render method, you can leave out the .php</p><p>extension.</p><p>By default Flight will look for a views directory for template files. You can set an alternate path for your</p><p>templates by setting the following config:</p></li><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 8/13</p><p>Flight::set('flight.views.path', '/path/to/views');</p><p>Layouts</p><p>It is common for websites to have a single layout template file with interchanging content. To render</p><p>content to be used in a layout, you can pass in an optional parameter to the render method.</p><p>Flight::render('header', array('heading' =&gt; 'Hello'), 'header_content');Flight::render('body', array('body' =&gt; 'World'), 'body_content');</p><p>Your view will then have saved variables called header_content and body_content. You can then render</p><p>your layout by doing:</p><p>Flight::render('layout', array('title' =&gt; 'Home Page'));</p><p>If the template files looks like this:</p><p>header.php:</p><p>body.php:</p><p>layout.php:</p><p>The output would be:</p><p>Home Page</p><p>HelloWorld</p><p>Custom Views</p><p>Flight allows you to swap out the default view engine simply by registering your own view class. Here's</p></li><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 9/13</p><p>how you would use the Smarty template engine for your views:</p><p>// Load Smarty libraryrequire './Smarty/libs/Smarty.class.php';</p><p>// Register Smarty as the view class// Also pass a callback function to configure Smarty on loadFlight::register('view', 'Smarty', array(), function($smarty){ $smarty-&gt;template_dir = './templates/'; $smarty-&gt;compile_dir = './templates_c/'; $smarty-&gt;config_dir = './config/'; $smarty-&gt;cache_dir = './cache/';});</p><p>// Assign template dataFlight::view()-&gt;assign('name', 'Bob');</p><p>// Display the templateFlight::view()-&gt;display('hello.tpl');</p><p>For completeness, you should also override Flight's default render method:</p><p>Flight::map('render', function($template, $data){ Flight::view()-&gt;assign($data); Flight::view()-&gt;display($template);});</p><p>Error Handling</p><p>Errors and Exceptions</p><p>All errors and exceptions are caught by Flight and passed to the error method. The default behavior is to</p><p>send a generic HTTP 500 Internal Server Error response with some error information.</p><p>You can override this behavior for your own needs:</p><p>Flight::map('error', function(Exception $ex){ // Handle error echo $ex-&gt;getTraceAsString();});</p><p>By default errors are not logged to the web server. You can enable this by changing the config:</p><p>Flight::set('flight.log_errors', true);</p><p>Not Found</p><p>When a URL can't be found, Flight calls the notFound method. The default behavior is to send an HTTP</p><p>404 Not Found response with a simple message.</p><p>You can override this behavior for your own needs:</p><p>Flight::map('notFound', function(){ // Handle not found</p></li><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 10/13</p><p>});</p><p>Redirects</p><p>You can redirect the current request by using the redirect method and passing in a new URL:</p><p>Flight::redirect('/new/location');</p><p>By default Flight sends a HTTP 303 status code. You can optionally set a custom code:</p><p>Flight::redirect('/new/location', 401);</p><p>Requests</p><p>Flight encapsulates the HTTP request into a single object, which can be accessed by doing:</p><p>$request = Flight::request();</p><p>The request object provides the following properties:</p><p>url - The URL being requestedbase - The parent subdirectory of the URLmethod - The request method (GET, POST, PUT, DELETE)referrer - The referrer URLip - IP address of the clientajax - Whether the request is an AJAX requestscheme - The server protocol (http, https)user_agent - Browser informationbody - Raw data from the request bodytype - The content typelength - The content lengthquery - Query string parametersdata - Post parameterscookies - Cookie parametersfiles - Uploaded filessecure - Whether the connection is secureaccept - HTTP accept parametersproxy_ip - Proxy IP address of the client</p><p>You can access the query, data, cookies, and files properties as arrays or objects.</p><p>So, to get a query string parameter, you can do:</p><p>$id = Flight::request()-&gt;query['id'];</p><p>Or you can do:</p><p>$id = Flight::request()-&gt;query-&gt;id;</p></li><li><p>3/10/2014 Flight - An extensible micro-framework for PHP</p><p>http://flightphp.com/learn#methods 11/13</p><p>HTTP Caching</p><p>Flight provides built-in support for HTTP level caching. If the caching condition is met, Flight will return</p><p>an HTTP 304 Not Modified response. The next time the client requests the same resource, they will be</p><p>prompted to use their locally cached version.</p><p>Last-Modified</p><p>You can use the lastModified method and pass in a UNIX timestamp to set the date and time a page</p><p>was last modified. The client will continue to use their cache until the last modified value is changed.</p><p>Flight::route('/news', function(){ Flight::lastModified(1234567890); echo 'This content will be cached.';});</p><p>ETag</p><p>ETag caching is similar to Last-Modified, except you can specify any id you want for the resource:</p><p>Flight::route('/news', function(){ Flight::etag('my-unique-id'); echo 'This content will be cached.';});</p><p>Keep in mind that calling either lastModified or etag will both set and check the cache value. If the</p><p>cache value is the same between requests, Flight will immediately send an HTTP 304 response and stop</p><p>processing.</p><p>Stopping</p><p>You can stop the framework at any point by calling the halt method:</p><p>Flight::halt();</p><p>You can also specify an optional HTTP status code and...</p></li></ul>