Boilerplate to use a Directus Instance to Build a Custom Website, Content will be Manage by Directus
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

917 lines
21 KiB

5 years ago
  1. # What is Flight?
  2. Flight is a fast, simple, extensible framework for PHP. Flight enables you to
  3. quickly and easily build RESTful web applications.
  4. ```php
  5. require 'flight/Flight.php';
  6. Flight::route('/', function(){
  7. echo 'hello world!';
  8. });
  9. Flight::start();
  10. ```
  11. [Learn more](http://flightphp.com/learn)
  12. # Requirements
  13. Flight requires `PHP 5.3` or greater.
  14. # License
  15. Flight is released under the [MIT](http://flightphp.com/license) license.
  16. # Installation
  17. 1\. Download the files.
  18. If you're using [Composer](https://getcomposer.org/), you can run the following command:
  19. ```
  20. composer require mikecao/flight
  21. ```
  22. OR you can [download](https://github.com/mikecao/flight/archive/master.zip) them directly
  23. and extract them to your web directory.
  24. 2\. Configure your webserver.
  25. For *Apache*, edit your `.htaccess` file with the following:
  26. ```
  27. RewriteEngine On
  28. RewriteCond %{REQUEST_FILENAME} !-f
  29. RewriteCond %{REQUEST_FILENAME} !-d
  30. RewriteRule ^(.*)$ index.php [QSA,L]
  31. ```
  32. **Note**: If you need to use flight in a subdirectory add the line `RewriteBase /subdir/` just after `RewriteEngine On`.
  33. For *Nginx*, add the following to your server declaration:
  34. ```
  35. server {
  36. location / {
  37. try_files $uri $uri/ /index.php;
  38. }
  39. }
  40. ```
  41. 3\. Create your `index.php` file.
  42. First include the framework.
  43. ```php
  44. require 'flight/Flight.php';
  45. ```
  46. If you're using Composer, run the autoloader instead.
  47. ```php
  48. require 'vendor/autoload.php';
  49. ```
  50. Then define a route and assign a function to handle the request.
  51. ```php
  52. Flight::route('/', function(){
  53. echo 'hello world!';
  54. });
  55. ```
  56. Finally, start the framework.
  57. ```php
  58. Flight::start();
  59. ```
  60. # Routing
  61. Routing in Flight is done by matching a URL pattern with a callback function.
  62. ```php
  63. Flight::route('/', function(){
  64. echo 'hello world!';
  65. });
  66. ```
  67. The callback can be any object that is callable. So you can use a regular function:
  68. ```php
  69. function hello(){
  70. echo 'hello world!';
  71. }
  72. Flight::route('/', 'hello');
  73. ```
  74. Or a class method:
  75. ```php
  76. class Greeting {
  77. public static function hello() {
  78. echo 'hello world!';
  79. }
  80. }
  81. Flight::route('/', array('Greeting', 'hello'));
  82. ```
  83. Or an object method:
  84. ```php
  85. class Greeting
  86. {
  87. public function __construct() {
  88. $this->name = 'John Doe';
  89. }
  90. public function hello() {
  91. echo "Hello, {$this->name}!";
  92. }
  93. }
  94. $greeting = new Greeting();
  95. Flight::route('/', array($greeting, 'hello'));
  96. ```
  97. Routes are matched in the order they are defined. The first route to match a
  98. request will be invoked.
  99. ## Method Routing
  100. By default, route patterns are matched against all request methods. You can respond
  101. to specific methods by placing an identifier before the URL.
  102. ```php
  103. Flight::route('GET /', function(){
  104. echo 'I received a GET request.';
  105. });
  106. Flight::route('POST /', function(){
  107. echo 'I received a POST request.';
  108. });
  109. ```
  110. You can also map multiple methods to a single callback by using a `|` delimiter:
  111. ```php
  112. Flight::route('GET|POST /', function(){
  113. echo 'I received either a GET or a POST request.';
  114. });
  115. ```
  116. ## Regular Expressions
  117. You can use regular expressions in your routes:
  118. ```php
  119. Flight::route('/user/[0-9]+', function(){
  120. // This will match /user/1234
  121. });
  122. ```
  123. ## Named Parameters
  124. You can specify named parameters in your routes which will be passed along to
  125. your callback function.
  126. ```php
  127. Flight::route('/@name/@id', function($name, $id){
  128. echo "hello, $name ($id)!";
  129. });
  130. ```
  131. You can also include regular expressions with your named parameters by using
  132. the `:` delimiter:
  133. ```php
  134. Flight::route('/@name/@id:[0-9]{3}', function($name, $id){
  135. // This will match /bob/123
  136. // But will not match /bob/12345
  137. });
  138. ```
  139. ## Optional Parameters
  140. You can specify named parameters that are optional for matching by wrapping
  141. segments in parentheses.
  142. ```php
  143. Flight::route('/blog(/@year(/@month(/@day)))', function($year, $month, $day){
  144. // This will match the following URLS:
  145. // /blog/2012/12/10
  146. // /blog/2012/12
  147. // /blog/2012
  148. // /blog
  149. });
  150. ```
  151. Any optional parameters that are not matched will be passed in as NULL.
  152. ## Wildcards
  153. Matching is only done on individual URL segments. If you want to match multiple
  154. segments you can use the `*` wildcard.
  155. ```php
  156. Flight::route('/blog/*', function(){
  157. // This will match /blog/2000/02/01
  158. });
  159. ```
  160. To route all requests to a single callback, you can do:
  161. ```php
  162. Flight::route('*', function(){
  163. // Do something
  164. });
  165. ```
  166. ## Passing
  167. You can pass execution on to the next matching route by returning `true` from
  168. your callback function.
  169. ```php
  170. Flight::route('/user/@name', function($name){
  171. // Check some condition
  172. if ($name != "Bob") {
  173. // Continue to next route
  174. return true;
  175. }
  176. });
  177. Flight::route('/user/*', function(){
  178. // This will get called
  179. });
  180. ```
  181. ## Route Info
  182. If you want to inspect the matching route information, you can request for the route
  183. object to be passed to your callback by passing in `true` as the third parameter in
  184. the route method. The route object will always be the last parameter passed to your
  185. callback function.
  186. ```php
  187. Flight::route('/', function($route){
  188. // Array of HTTP methods matched against
  189. $route->methods;
  190. // Array of named parameters
  191. $route->params;
  192. // Matching regular expression
  193. $route->regex;
  194. // Contains the contents of any '*' used in the URL pattern
  195. $route->splat;
  196. }, true);
  197. ```
  198. # Extending
  199. Flight is designed to be an extensible framework. The framework comes with a set
  200. of default methods and components, but it allows you to map your own methods,
  201. register your own classes, or even override existing classes and methods.
  202. ## Mapping Methods
  203. To map your own custom method, you use the `map` function:
  204. ```php
  205. // Map your method
  206. Flight::map('hello', function($name){
  207. echo "hello $name!";
  208. });
  209. // Call your custom method
  210. Flight::hello('Bob');
  211. ```
  212. ## Registering Classes
  213. To register your own class, you use the `register` function:
  214. ```php
  215. // Register your class
  216. Flight::register('user', 'User');
  217. // Get an instance of your class
  218. $user = Flight::user();
  219. ```
  220. The register method also allows you to pass along parameters to your class
  221. constructor. So when you load your custom class, it will come pre-initialized.
  222. You can define the constructor parameters by passing in an additional array.
  223. Here's an example of loading a database connection:
  224. ```php
  225. // Register class with constructor parameters
  226. Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'));
  227. // Get an instance of your class
  228. // This will create an object with the defined parameters
  229. //
  230. // new PDO('mysql:host=localhost;dbname=test','user','pass');
  231. //
  232. $db = Flight::db();
  233. ```
  234. If you pass in an additional callback parameter, it will be executed immediately
  235. after class construction. This allows you to perform any set up procedures for your
  236. new object. The callback function takes one parameter, an instance of the new object.
  237. ```php
  238. // The callback will be passed the object that was constructed
  239. Flight::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'), function($db){
  240. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  241. });
  242. ```
  243. By default, every time you load your class you will get a shared instance.
  244. To get a new instance of a class, simply pass in `false` as a parameter:
  245. ```php
  246. // Shared instance of the class
  247. $shared = Flight::db();
  248. // New instance of the class
  249. $new = Flight::db(false);
  250. ```
  251. Keep in mind that mapped methods have precedence over registered classes. If you
  252. declare both using the same name, only the mapped method will be invoked.
  253. # Overriding
  254. Flight allows you to override its default functionality to suit your own needs,
  255. without having to modify any code.
  256. For example, when Flight cannot match a URL to a route, it invokes the `notFound`
  257. method which sends a generic `HTTP 404` response. You can override this behavior
  258. by using the `map` method:
  259. ```php
  260. Flight::map('notFound', function(){
  261. // Display custom 404 page
  262. include 'errors/404.html';
  263. });
  264. ```
  265. Flight also allows you to replace core components of the framework.
  266. For example you can replace the default Router class with your own custom class:
  267. ```php
  268. // Register your custom class
  269. Flight::register('router', 'MyRouter');
  270. // When Flight loads the Router instance, it will load your class
  271. $myrouter = Flight::router();
  272. ```
  273. Framework methods like `map` and `register` however cannot be overridden. You will
  274. get an error if you try to do so.
  275. # Filtering
  276. Flight allows you to filter methods before and after they are called. There are no
  277. predefined hooks you need to memorize. You can filter any of the default framework
  278. methods as well as any custom methods that you've mapped.
  279. A filter function looks like this:
  280. ```php
  281. function(&$params, &$output) {
  282. // Filter code
  283. }
  284. ```
  285. Using the passed in variables you can manipulate the input parameters and/or the output.
  286. You can have a filter run before a method by doing:
  287. ```php
  288. Flight::before('start', function(&$params, &$output){
  289. // Do something
  290. });
  291. ```
  292. You can have a filter run after a method by doing:
  293. ```php
  294. Flight::after('start', function(&$params, &$output){
  295. // Do something
  296. });
  297. ```
  298. You can add as many filters as you want to any method. They will be called in the
  299. order that they are declared.
  300. Here's an example of the filtering process:
  301. ```php
  302. // Map a custom method
  303. Flight::map('hello', function($name){
  304. return "Hello, $name!";
  305. });
  306. // Add a before filter
  307. Flight::before('hello', function(&$params, &$output){
  308. // Manipulate the parameter
  309. $params[0] = 'Fred';
  310. });
  311. // Add an after filter
  312. Flight::after('hello', function(&$params, &$output){
  313. // Manipulate the output
  314. $output .= " Have a nice day!";
  315. });
  316. // Invoke the custom method
  317. echo Flight::hello('Bob');
  318. ```
  319. This should display:
  320. Hello Fred! Have a nice day!
  321. If you have defined multiple filters, you can break the chain by returning `false`
  322. in any of your filter functions:
  323. ```php
  324. Flight::before('start', function(&$params, &$output){
  325. echo 'one';
  326. });
  327. Flight::before('start', function(&$params, &$output){
  328. echo 'two';
  329. // This will end the chain
  330. return false;
  331. });
  332. // This will not get called
  333. Flight::before('start', function(&$params, &$output){
  334. echo 'three';
  335. });
  336. ```
  337. Note, core methods such as `map` and `register` cannot be filtered because they
  338. are called directly and not invoked dynamically.
  339. # Variables
  340. Flight allows you to save variables so that they can be used anywhere in your application.
  341. ```php
  342. // Save your variable
  343. Flight::set('id', 123);
  344. // Elsewhere in your application
  345. $id = Flight::get('id');
  346. ```
  347. To see if a variable has been set you can do:
  348. ```php
  349. if (Flight::has('id')) {
  350. // Do something
  351. }
  352. ```
  353. You can clear a variable by doing:
  354. ```php
  355. // Clears the id variable
  356. Flight::clear('id');
  357. // Clears all variables
  358. Flight::clear();
  359. ```
  360. Flight also uses variables for configuration purposes.
  361. ```php
  362. Flight::set('flight.log_errors', true);
  363. ```
  364. # Views
  365. Flight provides some basic templating functionality by default. To display a view
  366. template call the `render` method with the name of the template file and optional
  367. template data:
  368. ```php
  369. Flight::render('hello.php', array('name' => 'Bob'));
  370. ```
  371. The template data you pass in is automatically injected into the template and can
  372. be reference like a local variable. Template files are simply PHP files. If the
  373. content of the `hello.php` template file is:
  374. ```php
  375. Hello, '<?php echo $name; ?>'!
  376. ```
  377. The output would be:
  378. Hello, Bob!
  379. You can also manually set view variables by using the set method:
  380. ```php
  381. Flight::view()->set('name', 'Bob');
  382. ```
  383. The variable `name` is now available across all your views. So you can simply do:
  384. ```php
  385. Flight::render('hello');
  386. ```
  387. Note that when specifying the name of the template in the render method, you can
  388. leave out the `.php` extension.
  389. By default Flight will look for a `views` directory for template files. You can
  390. set an alternate path for your templates by setting the following config:
  391. ```php
  392. Flight::set('flight.views.path', '/path/to/views');
  393. ```
  394. ## Layouts
  395. It is common for websites to have a single layout template file with interchanging
  396. content. To render content to be used in a layout, you can pass in an optional
  397. parameter to the `render` method.
  398. ```php
  399. Flight::render('header', array('heading' => 'Hello'), 'header_content');
  400. Flight::render('body', array('body' => 'World'), 'body_content');
  401. ```
  402. Your view will then have saved variables called `header_content` and `body_content`.
  403. You can then render your layout by doing:
  404. ```php
  405. Flight::render('layout', array('title' => 'Home Page'));
  406. ```
  407. If the template files looks like this:
  408. `header.php`:
  409. ```php
  410. <h1><?php echo $heading; ?></h1>
  411. ```
  412. `body.php`:
  413. ```php
  414. <div><?php echo $body; ?></div>
  415. ```
  416. `layout.php`:
  417. ```php
  418. <html>
  419. <head>
  420. <title><?php echo $title; ?></title>
  421. </head>
  422. <body>
  423. <?php echo $header_content; ?>
  424. <?php echo $body_content; ?>
  425. </body>
  426. </html>
  427. ```
  428. The output would be:
  429. ```html
  430. <html>
  431. <head>
  432. <title>Home Page</title>
  433. </head>
  434. <body>
  435. <h1>Hello</h1>
  436. <div>World</div>
  437. </body>
  438. </html>
  439. ```
  440. ## Custom Views
  441. Flight allows you to swap out the default view engine simply by registering your
  442. own view class. Here's how you would use the [Smarty](http://www.smarty.net/)
  443. template engine for your views:
  444. ```php
  445. // Load Smarty library
  446. require './Smarty/libs/Smarty.class.php';
  447. // Register Smarty as the view class
  448. // Also pass a callback function to configure Smarty on load
  449. Flight::register('view', 'Smarty', array(), function($smarty){
  450. $smarty->template_dir = './templates/';
  451. $smarty->compile_dir = './templates_c/';
  452. $smarty->config_dir = './config/';
  453. $smarty->cache_dir = './cache/';
  454. });
  455. // Assign template data
  456. Flight::view()->assign('name', 'Bob');
  457. // Display the template
  458. Flight::view()->display('hello.tpl');
  459. ```
  460. For completeness, you should also override Flight's default render method:
  461. ```php
  462. Flight::map('render', function($template, $data){
  463. Flight::view()->assign($data);
  464. Flight::view()->display($template);
  465. });
  466. ```
  467. # Error Handling
  468. ## Errors and Exceptions
  469. All errors and exceptions are caught by Flight and passed to the `error` method.
  470. The default behavior is to send a generic `HTTP 500 Internal Server Error`
  471. response with some error information.
  472. You can override this behavior for your own needs:
  473. ```php
  474. Flight::map('error', function(Exception $ex){
  475. // Handle error
  476. echo $ex->getTraceAsString();
  477. });
  478. ```
  479. By default errors are not logged to the web server. You can enable this by
  480. changing the config:
  481. ```php
  482. Flight::set('flight.log_errors', true);
  483. ```
  484. ## Not Found
  485. When a URL can't be found, Flight calls the `notFound` method. The default
  486. behavior is to send an `HTTP 404 Not Found` response with a simple message.
  487. You can override this behavior for your own needs:
  488. ```php
  489. Flight::map('notFound', function(){
  490. // Handle not found
  491. });
  492. ```
  493. # Redirects
  494. You can redirect the current request by using the `redirect` method and passing
  495. in a new URL:
  496. ```php
  497. Flight::redirect('/new/location');
  498. ```
  499. By default Flight sends a HTTP 303 status code. You can optionally set a
  500. custom code:
  501. ```php
  502. Flight::redirect('/new/location', 401);
  503. ```
  504. # Requests
  505. Flight encapsulates the HTTP request into a single object, which can be
  506. accessed by doing:
  507. ```php
  508. $request = Flight::request();
  509. ```
  510. The request object provides the following properties:
  511. ```
  512. url - The URL being requested
  513. base - The parent subdirectory of the URL
  514. method - The request method (GET, POST, PUT, DELETE)
  515. referrer - The referrer URL
  516. ip - IP address of the client
  517. ajax - Whether the request is an AJAX request
  518. scheme - The server protocol (http, https)
  519. user_agent - Browser information
  520. type - The content type
  521. length - The content length
  522. query - Query string parameters
  523. data - Post data or JSON data
  524. cookies - Cookie data
  525. files - Uploaded files
  526. secure - Whether the connection is secure
  527. accept - HTTP accept parameters
  528. proxy_ip - Proxy IP address of the client
  529. ```
  530. You can access the `query`, `data`, `cookies`, and `files` properties
  531. as arrays or objects.
  532. So, to get a query string parameter, you can do:
  533. ```php
  534. $id = Flight::request()->query['id'];
  535. ```
  536. Or you can do:
  537. ```php
  538. $id = Flight::request()->query->id;
  539. ```
  540. ## RAW Request Body
  541. To get the raw HTTP request body, for example when dealing with PUT requests, you can do:
  542. ```php
  543. $body = Flight::request()->getBody();
  544. ```
  545. ## JSON Input
  546. If you send a request with the type `application/json` and the data `{"id": 123}` it will be available
  547. from the `data` property:
  548. ```php
  549. $id = Flight::request()->data->id;
  550. ```
  551. # HTTP Caching
  552. Flight provides built-in support for HTTP level caching. If the caching condition
  553. is met, Flight will return an HTTP `304 Not Modified` response. The next time the
  554. client requests the same resource, they will be prompted to use their locally
  555. cached version.
  556. ## Last-Modified
  557. You can use the `lastModified` method and pass in a UNIX timestamp to set the date
  558. and time a page was last modified. The client will continue to use their cache until
  559. the last modified value is changed.
  560. ```php
  561. Flight::route('/news', function(){
  562. Flight::lastModified(1234567890);
  563. echo 'This content will be cached.';
  564. });
  565. ```
  566. ## ETag
  567. `ETag` caching is similar to `Last-Modified`, except you can specify any id you
  568. want for the resource:
  569. ```php
  570. Flight::route('/news', function(){
  571. Flight::etag('my-unique-id');
  572. echo 'This content will be cached.';
  573. });
  574. ```
  575. Keep in mind that calling either `lastModified` or `etag` will both set and check the
  576. cache value. If the cache value is the same between requests, Flight will immediately
  577. send an `HTTP 304` response and stop processing.
  578. # Stopping
  579. You can stop the framework at any point by calling the `halt` method:
  580. ```php
  581. Flight::halt();
  582. ```
  583. You can also specify an optional `HTTP` status code and message:
  584. ```php
  585. Flight::halt(200, 'Be right back...');
  586. ```
  587. Calling `halt` will discard any response content up to that point. If you want to stop
  588. the framework and output the current response, use the `stop` method:
  589. ```php
  590. Flight::stop();
  591. ```
  592. # JSON
  593. Flight provides support for sending JSON and JSONP responses. To send a JSON response you
  594. pass some data to be JSON encoded:
  595. ```php
  596. Flight::json(array('id' => 123));
  597. ```
  598. For JSONP requests you, can optionally pass in the query parameter name you are
  599. using to define your callback function:
  600. ```php
  601. Flight::jsonp(array('id' => 123), 'q');
  602. ```
  603. So, when making a GET request using `?q=my_func`, you should receive the output:
  604. ```
  605. my_func({"id":123});
  606. ```
  607. If you don't pass in a query parameter name it will default to `jsonp`.
  608. # Configuration
  609. You can customize certain behaviors of Flight by setting configuration values
  610. through the `set` method.
  611. ```php
  612. Flight::set('flight.log_errors', true);
  613. ```
  614. The following is a list of all the available configuration settings:
  615. flight.base_url - Override the base url of the request. (default: null)
  616. flight.case_sensitive - Case sensitive matching for URLs. (default: false)
  617. flight.handle_errors - Allow Flight to handle all errors internally. (default: true)
  618. flight.log_errors - Log errors to the web server's error log file. (default: false)
  619. flight.views.path - Directory containing view template files. (default: ./views)
  620. flight.views.extension - View template file extension. (default: .php)
  621. # Framework Methods
  622. Flight is designed to be easy to use and understand. The following is the complete
  623. set of methods for the framework. It consists of core methods, which are regular
  624. static methods, and extensible methods, which are mapped methods that can be filtered
  625. or overridden.
  626. ## Core Methods
  627. ```php
  628. Flight::map($name, $callback) // Creates a custom framework method.
  629. Flight::register($name, $class, [$params], [$callback]) // Registers a class to a framework method.
  630. Flight::before($name, $callback) // Adds a filter before a framework method.
  631. Flight::after($name, $callback) // Adds a filter after a framework method.
  632. Flight::path($path) // Adds a path for autoloading classes.
  633. Flight::get($key) // Gets a variable.
  634. Flight::set($key, $value) // Sets a variable.
  635. Flight::has($key) // Checks if a variable is set.
  636. Flight::clear([$key]) // Clears a variable.
  637. Flight::init() // Initializes the framework to its default settings.
  638. Flight::app() // Gets the application object instance
  639. ```
  640. ## Extensible Methods
  641. ```php
  642. Flight::start() // Starts the framework.
  643. Flight::stop() // Stops the framework and sends a response.
  644. Flight::halt([$code], [$message]) // Stop the framework with an optional status code and message.
  645. Flight::route($pattern, $callback) // Maps a URL pattern to a callback.
  646. Flight::redirect($url, [$code]) // Redirects to another URL.
  647. Flight::render($file, [$data], [$key]) // Renders a template file.
  648. Flight::error($exception) // Sends an HTTP 500 response.
  649. Flight::notFound() // Sends an HTTP 404 response.
  650. Flight::etag($id, [$type]) // Performs ETag HTTP caching.
  651. Flight::lastModified($time) // Performs last modified HTTP caching.
  652. Flight::json($data, [$code], [$encode], [$charset], [$option]) // Sends a JSON response.
  653. Flight::jsonp($data, [$param], [$code], [$encode], [$charset], [$option]) // Sends a JSONP response.
  654. ```
  655. Any custom methods added with `map` and `register` can also be filtered.
  656. # Framework Instance
  657. Instead of running Flight as a global static class, you can optionally run it
  658. as an object instance.
  659. ```php
  660. require 'flight/autoload.php';
  661. use flight\Engine;
  662. $app = new Engine();
  663. $app->route('/', function(){
  664. echo 'hello world!';
  665. });
  666. $app->start();
  667. ```
  668. So instead of calling the static method, you would call the instance method with
  669. the same name on the Engine object.