Viewmodels
38 | 39 |As of version 1.7.2, Viewmodels are renamed to Presenters.
40 | 41 |For backward compatibility reasons, Viewmodel is now an alias for Presenter, application using the Viewmodel class will continue to work.
42 |├── favicon.ico ├── favicon.png ├── assets ├── img │ ├── fuel.png │ ├── clear.gif │ ├── handle.png │ ├── point.png │ ├── h-split.png │ ├── header-bg.jpg │ ├── nestedset.gif │ ├── profiler.png │ ├── v-split.png │ └── nestedset2.gif └── fonts │ ├── BebasNeue-webfont.eot │ ├── BebasNeue-webfont.ttf │ ├── BebasNeue-webfont.woff │ ├── DroidSans-Bold-webfont.eot │ ├── DroidSans-Bold-webfont.ttf │ └── DroidSans-Bold-webfont.woff ├── .gitignore ├── composer.json ├── general ├── viewmodels.html ├── controllers │ ├── hybrid.html │ └── template.html ├── tasks.html ├── polyfills.html ├── constants.html ├── classes.html ├── mvc.html ├── hmvc.html ├── packages.html ├── profiling.html └── models.html ├── packages ├── email │ └── troubleshooting.html ├── oil │ ├── server.html │ ├── console.html │ ├── refine.html │ ├── package.html │ └── intro.html ├── orm │ ├── observers │ │ ├── intro.html │ │ └── creating.html │ └── relations │ │ ├── belongs_to.html │ │ ├── has_one.html │ │ └── has_many.html ├── auth │ └── drivers.html └── parser │ └── intro.html ├── vendor ├── intro.html ├── phpquickprofiler.html ├── spyc.html ├── markdown.html ├── htmlawed.html └── phpseclib.html ├── classes ├── cache │ ├── advanced.html │ └── config.html ├── database │ ├── qb.html │ └── qb_delete.html ├── markdown.html ├── file │ ├── advanced.html │ └── intro.html ├── mongo │ └── introduction.html ├── theme │ └── advanced.html ├── crypt │ ├── config.html │ ├── usage.html │ └── advanced.html └── package.html ├── license.html ├── templates └── index.html ├── credits.html ├── requirements.html ├── index.html ├── contribute.html └── installation ├── download.html └── external.html /favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/favicon.ico -------------------------------------------------------------------------------- /favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/favicon.png -------------------------------------------------------------------------------- /assets/img/fuel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/img/fuel.png -------------------------------------------------------------------------------- /assets/img/clear.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/img/clear.gif -------------------------------------------------------------------------------- /assets/img/handle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/img/handle.png -------------------------------------------------------------------------------- /assets/img/point.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/img/point.png -------------------------------------------------------------------------------- /assets/img/h-split.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/img/h-split.png -------------------------------------------------------------------------------- /assets/img/header-bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/img/header-bg.jpg -------------------------------------------------------------------------------- /assets/img/nestedset.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/img/nestedset.gif -------------------------------------------------------------------------------- /assets/img/profiler.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/img/profiler.png -------------------------------------------------------------------------------- /assets/img/v-split.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/img/v-split.png -------------------------------------------------------------------------------- /assets/img/nestedset2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/img/nestedset2.gif -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | nbproject 3 | *.tmproj 4 | *.swp~ 5 | 6 | #intellij 7 | .idea 8 | /change.php 9 | -------------------------------------------------------------------------------- /assets/fonts/BebasNeue-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/fonts/BebasNeue-webfont.eot -------------------------------------------------------------------------------- /assets/fonts/BebasNeue-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/fonts/BebasNeue-webfont.ttf -------------------------------------------------------------------------------- /assets/fonts/BebasNeue-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/fonts/BebasNeue-webfont.woff -------------------------------------------------------------------------------- /assets/fonts/DroidSans-Bold-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/fonts/DroidSans-Bold-webfont.eot -------------------------------------------------------------------------------- /assets/fonts/DroidSans-Bold-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/fonts/DroidSans-Bold-webfont.ttf -------------------------------------------------------------------------------- /assets/fonts/DroidSans-Bold-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuel/docs/HEAD/assets/fonts/DroidSans-Bold-webfont.woff -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fuel/docs", 3 | "description" : "FuelPHP 1.x Documenataion", 4 | "type": "fuel-package", 5 | "homepage": "https://github.com/fuel/docs", 6 | "license": "MIT", 7 | "authors": [ 8 | { 9 | "name": "FuelPHP Development Team", 10 | "email": "team@fuelphp.com" 11 | } 12 | ], 13 | "require": { 14 | "composer/installers": "^2.3.0" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /general/viewmodels.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 6 | 7 | 8 | 9 | 12 | 13 |As of version 1.7.2, Viewmodels are renamed to Presenters.
40 | 41 |For backward compatibility reasons, Viewmodel is now an alias for Presenter, application using the Viewmodel class will continue to work.
42 |39 | The hybrid controller brings together the functionality of both the REST controller and the 40 | Template controller in a single base controller. 41 |
42 | 43 |44 | For more information about the Template or Rest functionality, see the Controller_Rest or Controller_Template pages. 45 |
46 | 47 |This page will try to list some common problems, and how to avoid or fix them.
39 | 40 |You need to use the following configuration:
43 | 44 |40 | With the oil server implementation, you don't even need to have a full blown webserver installed! It will use 41 | the webserver build into PHP as of version 5.4. Start it on the commandline, and use your browser to point to 42 | the hostname and port you've specified (by default, http://localhost:8000). 43 |
44 | 45 |$ php oil server
46 | Listening on http://localhost:8000
47 | Document root is public/
48 | Press Ctrl-C to quit.
49 |
50 | When you're finished, press Ctrl-C to terminate the server.
51 | 52 |41 | The FuelPHP core comes with several vendor packages pre-installed. Vendor packages are libraries from external parties that 42 | are integrated into the FuelPHP core. 43 |
44 | 45 |40 | The console is the quickest way to test out new classes, models and quick code without even having to open up an IDE. 41 | The shell is interactive but due to limitations in PHP it's not quite as interactive as the bash shell unless you 42 | enable the readline extension. Either way it works, readline just makes it better. 43 |
44 | 45 |$ php oil console
46 | Fuel 1.0.0-dev - PHP 5.3.3 (cli) (Aug 22 2010 19:27:08) [Darwin]
47 | >>> "Hello World!"
48 | Hello World!
49 | >>> 1+5
50 | 6
51 | >>> $i = 1
52 | >>> ++$i
53 | 2
54 | >>> json_encode(array('foo', 'bar'));
55 | ["foo","bar"]
56 | >>> $monkey = Model_Monkey::find('first');
57 | >>> $monkey->title
58 | Bobby the Gibbon
59 |
60 | The cache class allows you to cache the result of a resource heavy operation.
40 | 41 |Using cache as an object instance.
45 |$options = array(...); //These are the same as in the cache config file.
46 |
47 | $cache = Cache::forge('my_cache', $options)
48 | Data can then be saved to the cache using the set() function.
49 |$cache->set($myData, 604800);
50 | This sets the data in one block and sets the expiration time to one week (604800 seconds). If the second parameter is set to null then the cache will never expire.
51 |Data can be retrieved in the same way as when using Cache statically.
52 |41 | PHPQuickProfiler a small tool (think Firebug for PHP) to provide profiling and debugging related information to 42 | developers without needing them to add a lot of programmatic overhead to their code. Now, we only need to toggle 43 | one config setting to true and you have access to an automated tool to help create a faster and more consistent 44 | code review experience. 45 |
46 | 47 |You can find the original documentation here.
50 | 51 |54 | The PHPQuickProfiler vendor package is used by FuelPHP in the Profiler class, to display profiling output when the profiler is enabled. 55 |
56 | 57 |60 | You can add data to PHPQuickProfiler through the Profiler class methods. 61 |
62 | 63 |41 | spyc is a simple YAML parser library for PHP. 42 |
43 |44 | YAML(tm) is a human-friendly, cross language, Unicode based data serialization language designed around the common 45 | native data structures of agile programming languages. It is broadly useful for programming needs ranging from configuration 46 | files to Internet messaging to object persistence to data auditing. Together with the Unicode standard for characters, the 47 | YAML specification provides all the information necessary to understand YAML Version 1.1 and to creating programs that 48 | process YAML information. 49 |
50 | 51 |You can find the original spyc documentation here.
54 | 55 |58 | The spyc vendor package is used by FuelPHP in the Config and Lang class drivers, to load files in YAML format. 59 |
60 | 61 |64 | There is no direct access to the spyc package. 65 |
66 | 67 |41 | “Markdown” is two things: a plain text markup syntax, and a software tool that converts the plain text markup to HTML for publishing on the web. 42 |
43 |44 | The Markdown syntax allows you to write text naturally and format it without using HTML tags. More importantly: in Markdown format, your text 45 | stays enjoyable to read for a human being, and this is true enough that it makes a Markdown document publishable as-is, as plain text. 46 | If you are using text-formatted email, you already know some part of the syntax. 47 |
48 | 49 |You can find the original markdown documentation here.
52 | 53 |56 | The markdown vendor package is used by FuelPHP in the Markdown class, to render strings in markdown syntax. 57 |
58 | 59 |62 | You can access markdown through the Markdown::parse() method. 63 |
64 | 65 |The MIT License
39 | 40 |Copyright (c) 2010 - 2018 Fuel Development Team
41 | 42 |43 | Permission is hereby granted, free of charge, to any person obtaining a copy 44 | of this software and associated documentation files (the "Software"), to deal 45 | in the Software without restriction, including without limitation the rights 46 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 47 | copies of the Software, and to permit persons to whom the Software is 48 | furnished to do so, subject to the following conditions: 49 |
50 | 51 |52 | The above copyright notice and this permission notice shall be included in 53 | all copies or substantial portions of the Software. 54 |
55 | 56 |57 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 58 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 59 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 60 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 61 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 62 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 63 | THE SOFTWARE. 64 |
65 | 66 |39 | Note: 40 | At the time of writing the query builder classes are reworked so they can handle multiple sql dialects. 41 |
42 |43 | The abstraction of writing SQL for database queries is done by the Query Builder. The query builder 44 | consists a set of classes, each handling a specific part of the query building process. 45 |
46 |47 | Using the query builder is will go unnoticed most of the times as the DB class provides shortcuts for 48 | creating new query builder objects. It's advised to use these methods to get the right query builder. this is common 49 | practice and will keep your code readable. 50 |
51 | 52 |53 | Here are the classes that query builder consists of: 54 |
55 | 56 |Tasks are classes that can be run through the command line or set up as a cron job. They are generally used for background processes, timed tasks and maintenance tasks. Tasks can calls models and other classes just like controllers.
40 | 41 |In Fuel Tasks are put in the fuel/app/tasks directory. Below is an example of the task "example":
44 | 45 |namespace Fuel\Tasks;
46 |
47 | class Example
48 | {
49 |
50 | public function run($message = 'Hello!')
51 | {
52 | echo $message;
53 | }
54 | }
55 |
56 | That will be called via the refine utility within oil:
57 | 58 |$ php oil refine example "Good morning".
59 |
60 | When just the name of the task is used in the command, the method "run()" is referenced.
61 | 62 |You can add more methods to your task class to break a group of tasks down into more specific tasks which can be called separately.
65 | 66 |public function current_date()
67 | {
68 | echo date('Y-m-d');
69 | }
70 |
71 | We can then call this method using:
72 | 73 |$ php oil refine example:current_date
74 |
75 | 41 | htmLawed is a highly customizable single-file PHP script to make text secure, and standard- and admin policy-compliant 42 | for use in the body of HTML 4, XHTML 1 or 1.1, or generic XML documents. It is thus a configurable input (X)HTML filter, 43 | processor, purifier, sanitizer, beautifier, etc., and an alternative to the HTMLTidy application. 44 |
45 |46 | The lawing in of input text is needed to ensure that HTML code in the text is standard-compliant, does not introduce security 47 | vulnerabilities, and does not break the aesthetics, design or layout of web-pages. htmLawed tries to do this by, for example, 48 | making HTML well-formed with balanced and properly nested tags, neutralizing code that may be used for cross-site scripting 49 | (XSS) attacks, and allowing only specified HTML elements/tags and attributes. 50 |
51 | 52 |You can find the htmLawed documentation here.
55 | 56 |59 | The htmLawed vendor package is used by FuelPHP in the security class, to clean user input. 60 |
61 | 62 |65 | You can access htmLawed through the Security::xss_clean() method. 66 |
67 | 68 |41 | The PHP Secure Communications Library contains LGPL-licensed pure-PHP implementations of arbitrary-precision integers, 42 | fully PKCS#1 (v2.1) compliant RSA, DES, 3DES, RC4, Rijndael, AES, SSH-1, SSH-2, and SFTP. This book discusses how to use them. 43 |
44 | 45 |You can find the original PHPSecLib documentation here.
48 | 49 |52 | The PHPSecLib vendor package is used by FuelPHP in the Crypt class, to generate secure hashes, and in the Auth package, which uses PBKDF2. 53 |
54 | 55 |58 | For use in your application the PHPSecLib package has been converted to a namespaced, autoloader friendly library. 59 | You can use it directly from your application. 60 |
61 |<?php
62 | /**
63 | * Example controller that does an SSH login
64 | */
65 |
66 | class Controller_Ssh extends Controller
67 | {
68 | public function action_index()
69 | {
70 | // connect to my server
71 | $ssh = new \phpseclib\Net\SSH2('myserver.example.org');
72 |
73 | // login
74 | if ( ! $ssh->login('username', 'password'))
75 | {
76 | throw new \Exception('ssh login failed');
77 | }
78 |
79 | // return the view that formats the directory list
80 | return View::forge('ssh/dirinfo', array(
81 | 'pwd' => $ssh->exec('pwd'),
82 | 'info' => $ssh->exec('ls -la'),
83 | ));
84 | }
85 | }
86 |
87 |
88 | 40 | Fuel provides polyfills for popular functions added to PHP after the release of PHP 5.3. 41 |
42 | 43 || Function | 47 |Description | 48 |
|---|---|
| array_first() | 51 |52 | Returns the first value from an array. 53 | Introduced in PHP 8.5. 54 | | 55 |
| array_last() | 58 |59 | Returns the last value from an array. 60 | Introduced in PHP 8.5. 61 | | 62 |
| array_key_first() | 65 |66 | Returns the first key from an array. 67 | Introduced in PHP 7.3. 68 | | 69 |
| array_key_last() | 72 |73 | Returns the last key from an array. 74 | Introduced in PHP 7.3. 75 | | 76 |
| hash_pbkdf2() | 79 |80 | Implements PBKDF2 hashing. 81 | Introduced in PHP 5.5. 82 | | 83 |
| json_validate() | 86 |87 | Checks if a string contains valid JSON. 88 | Introduced in PHP 8.3. 89 | | 90 |
| http_build_url() | 93 |94 | The reverse function of parse_url(). It is defined in a PECL extension, but not every server has the extension loaded, and not everyone has the option to change installed PHP modules. 95 | Defined in pecl_http >= 0.21.0. 96 | | 97 |
TODO: Write home page copy.
36 | 37 |Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent non urna vitae erat ultricies malesuada. Phasellus ut semper mauris. Morbi lobortis sem eu tortor fringilla cursus. Nullam consequat commodo massa, vitae aliquet purus pretium vel. Pellentesque eleifend gravida lacus, ac ullamcorper sem suscipit vel. Mauris nec ultrices felis. Suspendisse aliquet, augue vitae sollicitudin pharetra, ante dolor imperdiet risus, sed tincidunt sem leo vestibulum leo. Ut quis quam arcu, non varius sapien. Morbi pharetra, lorem in commodo imperdiet, velit sem ultrices nisl, ultrices accumsan ante felis ut turpis. Fusce in nibh nec orci consequat molestie. Nunc semper congue vestibulum. Aliquam ac auctor felis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
38 | 39 |Suspendisse bibendum sapien sed justo tincidunt dapibus. Duis non iaculis lorem. Suspendisse est ante, volutpat quis hendrerit pulvinar, pharetra vel tortor. Suspendisse sed augue tortor. Aliquam erat volutpat. Phasellus vel enim dui, quis faucibus augue. Suspendisse consequat sagittis sagittis. Duis semper tempor ante et ultrices. Donec vulputate nibh in urna tempor vel feugiat tortor imperdiet. Donec condimentum augue a eros tincidunt sagittis. Nulla sit amet magna enim, at ultricies ipsum. Morbi non ante vitae tellus interdum auctor quis sed augue. Phasellus lacus erat, gravida ut gravida eget, accumsan ut enim. Nunc at dui neque. In non libero in elit pretium aliquet sit amet sed massa. Nunc ut augue sit amet sem suscipit malesuada eu id ante. Proin congue, nisl a imperdiet tincidunt, nunc dui posuere metus, nec ornare arcu felis et justo. Praesent imperdiet, nulla eu consequat facilisis, velit nunc congue metus, non luctus lacus sapien nec nunc. Aliquam euismod lacus quis justo consequat condimentum. Morbi sem elit, gravida sed tempor fermentum, euismod nec nisi.
40 | 41 |Code would go here...
42 |
43 | Orm is short for Object
39 | Relational Mapper which does 2 things: it maps your database table rows to objects and it allows you
40 | to establish relations between those objects.
41 | It follows closely the
42 | Active Record Pattern, but was also influenced by other systems.
An event based system to allow you to add behavior to specific events. When an event is observed the 48 | Orm will automatically call all the added observers to see if there's anything for them to do.
49 | 50 |You can add observers in 2 ways: just add the name to have the observer called for all events or with
61 | the observer as name and an array of specific events for which the observer is called.
62 | When the Observer is in the same namespace as the Model and prefixed with Observer_ you can
63 | leave out the "Observer_" prefix. In all other cases you have to provide the full classname.
class Model_Article
66 | {
67 | protected static $_observers = array(
68 | 'example', // will call Observer_Example class for all events
69 | 'Orm\\Observer_CreatedOn' => array(
70 | 'events' => array('before_insert'), // will only call Orm\Observer_CreatedOn at before_insert event
71 | )
72 | );
73 | }
74 | A plain text to HTML converter, originally by John Gruber. FuelPHP uses a ported and extended version by Michel Fortin.
40 | 41 |Parses Markdown and returns HTML.
44 || Static | 48 |Yes | 49 |||||||
|---|---|---|---|---|---|---|---|
| Parameters | 52 |
53 |
|
66 | ||||||
| Returns | 69 |string | 70 |||||||
| Example | 73 |
74 |
84 | Returns 85 |
93 | |
94 |
These are the developers that make commits on a near-daily basis, and make all final decisions about the framework.
39 |45 | Do you think you have what it takes to become a Core Developer? Start with discussing the future of the 46 | framework in IRC, send in pull requests for open issues, attack one of the many approved feature requests, or 47 | join the work for the new 2.0 version. 48 |
49 | 50 |52 | Unfortunately, times change, and people move on. We would like to thank the following people for their efforts as core developer 53 | of the FuelPHP framework. Without them, it would not be what it is today! 54 |
55 |Up to date contributor lists are per repo on github:
64 |39 | Fuel has four constants in the global namespace to direct you to important directories. Fuel uses them internally to locate classes and other files. 40 | These constants are set in public/index.php. 41 |
42 | 43 |44 | Note: When you move any of fuel's prime folders (app, core, public, packages) be sure to update your index.php to direct fuel to the right paths. 45 |
46 | 47 || Key | 51 |Description | 52 |
|---|---|
| APPPATH | 55 |56 | Path to the application directory (/path/to/fuel/app). 57 | This is where your application directories and code reside. 58 | | 59 |
| COREPATH | 62 |63 | Path to the core directory (/path/to/fuel/core). 64 | This is where all the Fuel classes live. 65 | | 66 |
| DOCROOT | 69 |70 | Path to the location where the 'startup script' is. 71 | For your web application, path to the public directory (/path/to/public). 72 | This is where index.php resides. Everything accessible to user lives and is accessible via the browser. 73 | For oil command, path to where oil command resides. 74 | | 75 |
| PKGPATH | 78 |79 | Path to the packages directory (/path/to/fuel/packages). 80 | This is where your packages are installed (when installed through oil). 81 | | 82 |
| VENDORPATH | 85 |86 | Path to the composer root directory (/path/to/fuel/vendor). 87 | This is where your composer installs the libraries downloaded from packagist.org. 88 | | 89 |
94 | Note: When you use the Oil package, you have to make the same changes in the 'oil' file in the docroot of your website. 95 |
96 | 97 |98 | Note: When you want to run unit tests, you have to make the same changes in the 'phpunit.xml' file in the fuelphp core folder. 99 |
100 |48 | Fuel uses functionality that PHP defines as "extensions". To avoid any possible compatibility issues, Fuel only uses extensions that 49 | are part of the PHP code as documented on the PHP website. If extensions are used that are part of the 50 | PECL repository (which need to be installed manually by a system administrator), Fuel will use them if present, and work around it if not. 51 |
52 |This is a list of extensions used, and the classes that use them:
53 || Extension | 57 |Used in | 58 |Comments | 59 |
|---|---|---|
| fileinfo | 62 |Upload | 63 |Documentation. 64 | Note that on Windows platforms, a manual installation of a DLL might be needed. |
65 |
| mbstring | 68 |n/a | 69 |Documentation. 70 | If not present, the framework has no multibyte support. You can check the MBSTRING constant to see if your installation has multibyte support enabled. |
71 |
| mcrypt | 74 |Crypt | 75 |Documentation. 76 | If not present, PHPSecLib is used to emulate its functionality. |
77 |
Orm is short for Object
38 | Relational Mapper which does 2 things: it maps your database table rows to objects and it allows you
39 | to establish relations between those objects.
40 | It follows closely the
41 | Active Record Pattern, but was also influenced by other systems.
Has the primary key of the relation kept in its table, belongs to 1 related object. This is the other 47 | side of a HasOne or HasMany relation.
48 | 49 |Let's say we have a model Model_Comment and it belongs to a Model_Post 52 | (which in turn has many comments) the ID of the Model_Post is saved with the Model_Comment 53 | instance in its own table. This means the comments table will have a column 54 | post_id (or something else you configure). If you keep to the defaults all you need to do 55 | is add 'post' to the $_belongs_to static property of the Model_Comment:
56 | 57 |protected static $_belongs_to = array('post');
58 |
59 | Below are examples for establishing and breaking belongs-to relations:
60 | 61 |// both main and related object are new:
62 | $comment = new Model_Comment();
63 | $comment->post = new Model_Post();
64 | $comment->save();
65 |
66 | // both main and related object already exist
67 | $comment = Model_Comment::find(6);
68 | $comment->post = Model_Post::find(1);
69 | $comment->save();
70 |
71 | // break the relationship established above
72 | $comment = Model_Comment::find(6);
73 | $comment->post = null;
74 | $comment->save();
75 |
76 | // in a Model_Comment which belong to a post
79 | protected static $_belongs_to = array(
80 | 'post' => array(
81 | 'key_from' => 'post_id',
82 | 'model_to' => 'Model_Post',
83 | 'key_to' => 'id',
84 | 'cascade_save' => true,
85 | 'constraint' => \Orm\Relation::CONSTRAINT_SETDEFAULT,
86 | )
87 | );
88 | Orm is short for Object
38 | Relational Mapper which does 2 things: it maps your database table rows to objects and it allows you
39 | to establish relations between those objects.
40 | It follows closely the
41 | Active Record Pattern, but was also influenced by other systems.
Specifies a one-to-one relationship to another model. The target model must include a 47 | "Belongs To" reference to the current model to allow the inverse 48 | relationship.
49 | 50 |Let's say we have a model Model_User and it has one a Model_Profile 53 | (which in turn belongs to the user). The ID of the Model_User is saved with the Model_Profile 54 | instance in its own table. This means the profiles table will have a column 55 | user_id (or something else you configure), while the user table won't mention the profile. 56 | If you keep to the defaults all you need to do is add 'profile' to the 57 | $_has_one static property of the Model_User:
58 | 59 |protected static $_has_one = array('profile');
60 |
61 | Below are examples for establishing and breaking has-one relations:
62 | 63 |// both main and related object are new:
64 | $user = new Model_User();
65 | $user->profile = new Model_Profile();
66 | $user->save();
67 |
68 | // both main and related object already exist
69 | $user = Model_User::find(6);
70 | $user->profile = Model_Profile::find(1);
71 | $user->save();
72 |
73 | // break the relationship established above
74 | $user = Model_User::find(6);
75 | $user->profile = null;
76 | $user->save();
77 |
78 | // in a Model_User which has one profile
81 | protected static $_has_one = array(
82 | 'profile' => array(
83 | 'key_from' => 'id',
84 | 'model_to' => 'Model_Profile',
85 | 'key_to' => 'user_id',
86 | 'cascade_save' => true,
87 | 'constraint' => \Orm\Relation::CONSTRAINT_SETDEFAULT,
88 | )
89 | );
90 | 41 | Refine is a tool that lets you run tasks. The idea behind the name is you "refine" Oil to make Fuel. You can read more 42 | specifically about Tasks to see how they are made and what they can be used for. 43 |
44 | 45 |48 | FuelPHP comes with several tasks to make your life just that little bit easier: 49 |
50 |git to clone the repositories.59 | All tasks will provide some help information when you run them with the help command: 60 |
61 |$ php oil refine <taskname>:help
62 | or
63 |$ php oil refine <taskname --help
64 |
65 | An example task called robots can be found in fuel/app/tasks/.
68 | 69 |$ php oil refine robots
70 |
71 | "KILL ALL HUMANS!"
72 | _____ /
73 | /_____\
74 | ____[\*---*/]____
75 | /\ #\ \_____/ /# /\
76 | / \# \_.---._/ #/ \
77 | / /|\ | | /|\ \
78 | /___/ | | | | | | \___\
79 | | | | | |---| | | | |
80 | |__| \_| |_#_| |_/ |__|
81 | //\\ <\ _//^\\_ /> //\\
82 | \||/ |\//// \\\\/| \||/
83 | | | | |
84 | |---| |---|
85 | |---| |---|
86 | | | | |
87 | |___| |___|
88 | / \ / \
89 | |_____| |_____|
90 | |HHHHH| |HHHHH|
91 |
92 |
93 | 94 | Not the most useful example in the world, but it works as a useful example. But you can use 95 | the Cli class to make things more interactive or just run basic model 96 | interaction for cron jobs. 97 |
98 | 99 |Orm is short for Object
38 | Relational Mapper which does 2 things: it maps your database table rows to objects and it allows you
39 | to establish relations between those objects.
40 | It follows closely the
41 | Active Record Pattern, but was also influenced by other systems.
Specifies a one-to-many relationship to another model. The target model must include a 47 | "Belongs To" reference to the current model to allow the inverse 48 | relationship.
49 | 50 |Let's say we have a model Model_Post and it has many Model_Comments 53 | (which in turn belong to the post). The ID of the Model_Post is saved with the Model_Comment 54 | instance in its own table. This means the comments table will have a column 55 | post_id (or something else you configure), while the posts table won't mention the comments. 56 | If you keep to the defaults all you need to do is add 'comments' to the 57 | $_has_many static property of the Model_User:
58 | 59 |protected static $_has_many = array('comments');
60 |
61 | Below are examples for establishing and breaking has-many relations:
62 | 63 |// both main and related object are new:
64 | $post = new Model_Post();
65 | $post->comments[] = new Model_Comment();
66 | $post->save();
67 |
68 | // both main and related object already exist
69 | $post = Model_Post::find(1);
70 | $post->comments[6] = Model_Comment::find(6); // assigning it to comments[6] is not required but recommended
71 | $post->save();
72 |
73 | // break the relationship established above
74 | $post = Model_Post::find(1);
75 | unset($post->comments[6]);
76 | $post->save();
77 |
78 | // in a Model_Post which has many comments
81 | protected static $_has_many = array(
82 | 'comments' => array(
83 | 'key_from' => 'id',
84 | 'model_to' => 'Model_Comment',
85 | 'key_to' => 'post_id',
86 | 'cascade_save' => true,
87 | 'constraint' => \Orm\Relation::CONSTRAINT_SETDEFAULT,
88 | )
89 | );
90 | 39 | FuelPHP is a simple, flexible, community driven PHP 5 web framework. It was born out of the frustrations people have with the current available frameworks and developed 40 | with support from a community of developers. FuelPHP is extremely portable, works on almost any server and prides itself on clean syntax. 41 |
42 | 43 |If you value your time and want to get things up and running in seconds instead of minutes, you can use our quick installer instead. Using the curl library, you can install a very basic version of oil. From there you can create new full applications of Fuel.
46 | 47 |# quick install oil from the web
48 | $ curl https://get.fuelphp.com/oil | sh
49 | # now that oil is installed, create a blog project in a directory called Sites
50 | $ cd Sites/
51 | $ oil create blog
52 |
53 | 54 | For more information, see the installation page. 55 |
56 | 57 |60 | If you can't use the quick installation method, you can also install FuelPHP manually. 61 | You will find detailed instructions on the installation page. 62 |
63 | 64 |76 | All the documentation is avaliable as a static download here 77 |
78 | 79 |82 | We provide full API documentation of all classes online. 83 |
84 | 85 |88 | This documentation reflects the state of the documentation at the time of the latest official FuelPHP release. 89 | For documentation of Fuel's bleeding edge, see our Develop Branch Documentation. 90 |
91 | 92 |41 | Packages can be installed and downloaded manually but with the help of the package command it can work much quicker. It does this 42 | by looking for packages within a list of sources defined in fuel/core/config/package.php and like any other config file can 43 | be edited there or copied to the fuel/app/config folder. 44 |
45 | 46 |47 | Oil is smart, so it will check to see if you have Git installed on your computer before it does anything with the package command. 48 | If you do have Git installed Oil will install a package as a Git repository instead of directly downloading the files, meaning 49 | updates, new releases and tracking custom changes to packages could not be easier. 50 |
51 | 52 |$ php oil package install test-package
55 | Downloading package: git://github.com/philsturgeon/fuel-test-package.git
56 | remote: Counting objects: 13, done.
57 | remote: Compressing objects: 100% (11/11), done.
58 | remote: Total 13 (delta 3), reused 0 (delta 0)
59 | Receiving objects: 100% (13/13), 10.85 KiB, done.
60 | Resolving deltas: 100% (3/3), done.
61 |
62 | Cloning into /Users/phil/Sites/fuel/fuel/packages/test-package...
63 |
64 | 65 | If Git is not installed, or the --direct flag is provided then a ZIP file of the package will be downloaded and unzipped 66 | to fuel/packages/packagename. 67 |
68 | 69 |$ php oil package install test-package --direct
70 | Downloading package: http://github.com/philsturgeon/fuel-test-package/zipball/master
71 | DOCROOT/fuel/packages/test-package/LICENSE.txt
72 | DOCROOT/fuel/packages/test-package/README
73 | DOCROOT/fuel/packages/test-package/classes/association.php
74 | DOCROOT/fuel/packages/test-package/classes/belongsto.php
75 | DOCROOT/fuel/packages/test-package/classes/exception.php
76 | DOCROOT/fuel/packages/test-package/classes/hasmany.php
77 | DOCROOT/fuel/packages/test-package/classes/hasone.php
78 | DOCROOT/fuel/packages/test-package/classes/model.php
79 |
80 | $ php oil package uninstall test-package
83 | Uninstalling package "test-package"
84 |
85 | Note: Unlike install there is no difference here if Git is installed, it will delete all the same.
86 | 87 |Coming soon...
90 | 91 |A class is just a normal PHP class. It doesn't need to extend anything or follow any conventions other than the naming convention which is the same as all other classes in Fuel.
41 | 42 |class Session
43 |
44 | That will be loaded from app/classes/session.php.
45 | 46 |Unlike some other frameworks classes do not need to be loaded manually. They will be auto-loaded when you refer to them in your code (Controllers, Models, etc).
49 | 50 |Just like Controllers, classes must be lower-case with first-letter upper case, while underscores will put the class into a sub-directory.
53 | 54 |Class Session_Driver
55 |
56 | That will be loaded from app/classes/session/driver.php
57 | 58 |61 | To determine which PHP file to load, FuelPHP's autoloader will treat namespaces and class names with underscores exactly the same. 62 | This means that for classes in sub-directories, you can mix-and-match namespaces and underscores to suit your needs. 63 |
64 | 65 |Take for example a class in the file app/classes/core/system/messages.php. The class in this file can be defined as:
66 | 67 |// global namespace, fully underscored class name
68 | class Core_System_Messages {}
69 |
70 | // combine a namespace and underscores
71 | namespace Core;
72 | class System_Messages {}
73 |
74 | // or fully namespaced
75 | namespace Core\System;
76 | class Messages {}
77 |
78 |
79 | 80 | The first method is the one most commonly used and easiest to understand. The namespaced versions are particularly handy if you 81 | combine them with the Use statement in the classes that use the defined class. 82 |
83 | 84 |It is possible to have Fuel's autoloader perform certain automated tasks once a class is loaded,
88 | sort of like what __construct() does for instances of a class. You do this by adding
89 | a public static _init() method to the class.
class Example {
92 | public static function _init()
93 | {
94 | // this is called upon loading the class
95 | }
96 | }
97 |
98 | If a loaded class has its own _init() method and a parent must be loaded
99 | alongside it, that parent's init method isn't called unless you call it using
100 | parent::_init();
MVC is an approach to separating your code depending on what role it plays in your application. In the 41 | application flow it starts with a controller that is loaded. That Controller executes a method which retrieves 42 | data using Models. Once it is done the controller decides what View to load, which contains the output your 43 | visitors get to see.
44 | 45 |Controller classes are located in APPPATH/classes/controller
48 | 49 |Fuel's routing decides based on the requested URL what controller to load and what method to call upon it. 50 | This is where your application starts working. The Controller decides what actions to take, what to do with any 51 | user input, what data gets manipulated and which View is shown to the user. The Controller does none of these 52 | things itself however; it calls upon Models and Classes to do the work.
53 | 54 |Read more about Controllers.
55 | 56 |Model classes are located in APPPATH/classes/model
59 | 60 |Whenever data needs to be retrieved, manipulated or deleted this should always be done by a model. A Model 61 | is a representation of some kind of data and has the methods to change them. For example: you never put SQL 62 | queries in a Controller, those are put in the Model and the Controller will call upon the Model to execute 63 | the queries. This way if your database changes you won't need to change all your Controllers but just the 64 | Model that acts upon it.
65 | 66 |Read more about Models.
67 | 68 |Views are located in APPPATH/views
71 | 72 |Views contain your HTML, which should never be found in your Controllers or any other class that is not
73 | specifically meant to create output. By separating your layout from your logic you ensure that when you decide
74 | to change your layout you only have to change the views and won't have to care about the Controllers.
75 | Views should thus contain little more than echo and foreach usage of PHP.
Read more about Views.
80 | 81 |Presenter classes are located in APPPATH/classes/presenter
84 | 85 |Once your application gets more complex you'll discover that it gets hard to decide if a piece of logic 86 | really belongs in the Controller, what if it is very specifically about the View and has little to do with your 87 | application logic? This is where Presenters come in; they are the glue between your controllers and your 88 | views.
89 | 90 |Read more about Presenters.
91 | 92 |41 | Fuel is a community driven framework and is open for contributions from anyone who feels they 42 | can improve it or add a feature that will bring the framework to a higher level. There 43 | are multiple forms in which this can be achieved. From writing tutorials, writing and 44 | releasing packages, to contributing to the official parts of Fuel (Core, Orm, Docs, etc..). 45 |
46 | 47 |50 | When you encounter a bug or see one in the issues list that you can or have resolved, 51 | and you want to contribute it back to the framework. Use GitHub to send a pull request. 52 | Depending on which version you are running the branch you pull on. Follow the next couple 53 | of steps to when you request a pull: 54 |
55 | 56 |$ git checkout -b 1.9/develop origin/1.9/develop
68 | $ git commit -m "This is my awesome description."
73 | $ git push
77 | You can find this procedure described in more detail on Github.
91 | 92 |95 | Non-bug contributions are new features, optimizations and all other alterations. All of these request must be made on the 96 | latest development branch. So pull the 1.9/develop branch, make the changes and request a pull. 97 |
98 |99 | For large and/or completely new features, or features that will take some time to complete, it might be wise 100 | to setup a separate feature branch. Contact one of the core developers via email or on IRC to discuss the options. 101 |
102 | 103 |39 | HMVC requests are a great way to separate logic and re-use controller logic in multiple places. 40 | One common use of this is when you use a theme or template engine to generate your pages, 41 | where every page is divided into sections, and sections are populated by widgets. 42 | By using modules to produce the widget output, you can create a highly modular application with easy to re-use components. 43 |
44 | 45 |You call a module controller method using the Request class:
46 |// fetch the output of a controller
47 | $widget = Request::forge('mycontroller/mymethod/parms')->execute();
48 | echo $widget;
49 |
50 | // or fetch the output of a module
51 | $widget = Request::forge('mymodule/mycontroller/mymethod/parms', false)->execute();
52 | echo $widget;
53 |
54 | // and if you need to pass in some data
55 | $widget = Request::forge('mymodule/mycontroller/mymethod/parms', false)->execute(array('tree'=>'apple'));
56 | echo $widget;
57 |
58 |
59 | 60 | By default, all requests made are processed by Fuel's routing engine. If you want to request something that isn't routable 61 | (for example because you don't want a browser to request it), you should pass 'false' as second parameter 62 | to the forge() call. If you don't you will end up with a 404 error when you execute the request! 63 |
64 | 65 |66 | Loading views in HMVC request is the same as in normal requests and controllers accessed by HMVC request 67 | are also approachable via the browser. However, in some cases you may not want the component (for example, a widget) 68 | to be accessed through the browser. In those cases, you'll want to check if the request is made through HMVC or the browser. 69 | The following example shows you how to check for a HMVC request: 70 |
71 | 72 |<?php
73 |
74 | class Controller_Widget extends Controller
75 | {
76 |
77 | public function action_show()
78 | {
79 | if( ! Request::is_hmvc())
80 | {
81 | // this is the main request
82 | }
83 | else
84 | {
85 | // this is a HMVC request
86 | }
87 | }
88 |
89 | }
90 |
91 | 94 | When a 404 occurs during a HMVC request, a HttpNotFoundException is thrown. If uncaught, it will trigger 95 | the load of the frameworks default 404 page. However, you can prevent this and handle the 404 96 | yourself: 97 |
98 | 99 |try
100 | {
101 | \Request::forge('this_will_fail');
102 | }
103 | catch (HttpNotFoundException $e)
104 | {
105 | // deal with it
106 | }
107 |
108 |
109 | If you want to access other Requests, you can traverse them using two methods: 112 | $request->parent() and $request->children(). The parent is the Request during 113 | which the current Request was created (null for the main Request). The children are all the Requests 114 | created during the current Request.
115 | 116 |The Oil utility is a special package command can be used in several ways to facilitate quick development, help with 39 | testing your application and for running Tasks.
40 | 41 |Oil is an optional command line utility designed to help speed up development by providing several functions:
44 | 45 |55 | Each of these commands works in a different way to achieve different things, but before getting into them it's best to make sure 56 | you are in the correct folder and oil is available and running. 57 |
58 | 59 |$ cd Sites/fuel
60 | $ php oil -v
61 | Fuel: 1.2
62 |
63 | 66 | Oil won’t use any instructions you’ve made for HTTP requests, such as defining the server environment using .htaccess. Oil will use whichever environment is the default unless you instruct it. 67 |
68 | 69 |$ FUEL_ENV=production php oil refine migrate
70 |
71 | In place of production you can use any of the defined environments.
Oil contains its own basic documentation which can be found by typing the command:
76 | 77 |$ php oil help
78 |
79 | Usage:
80 | php oil [cell|console|generate|package|refine|help|server|test]
81 |
82 | Runtime options:
83 | -f, [--force] # Overwrite files that already exist
84 | -s, [--skip] # Skip files that already exist
85 | -q, [--quiet] # Supress status output
86 | -t, [--speak] # Speak errors in a robot voice
87 |
88 | Description:
89 | The 'oil' command can be used in several ways to facilitate quick development, help with
90 | testing your application and for running Tasks.
91 |
92 | Environment:
93 | If you want to specify a specific environment oil has to run in, overload the environment
94 | variable on the commandline: FUEL_ENV=staging php oil <commands>
95 |
96 | More information:
97 | You can pass the parameter "help" to each of the defined command to get information
98 | about that specific command: php oil package help
99 |
100 | Documentation:
101 | http://docs.fuelphp.com/packages/oil/intro.html
102 |
103 |
104 |
105 | Each of these commands has its own help section which can be found by typing:
106 | 107 |$ php oil generate help
108 |
109 | 42 | Aside from the basic static usage of the File class there are also more 43 | complex options available. The first are areas which are basically basepaths it 44 | cannot act outside of and have some configuration options. And when using the File class's methods 45 | on an area they will return objects wrapping directories & files. 46 |
47 | 48 |53 | File areas are used to influence file system behaviour. By setting basic restrictions you can 54 | set boundaries to allow a flexible use inside those limits without worrying about unauthorized 55 | access of files and directories. 56 |
57 | 58 |
60 | By default file areas have unlimited access through all directories. (The default area is defined as base_config in File config file.) There are two ways to set
61 | these configuration values. The quickest way is to pass an array intro the
62 | File::forge() method.
63 |
$config = array(
66 | 'basedir' => DOCROOT.'uploads',
67 | 'use_locks' => true,
68 | );
69 |
70 | $area = \File::forge($config);
71 |
72 | 73 | A more centralized way is by defining an area (or more) inside your File config file. To do so, 74 | copy core/config/file.php into app/config/file.php (or create a new one) and 75 | define your area inside the 'areas' array. Now you can get the area by supplying the 76 | string identifier to the File::forge() method. 77 |
78 | 79 |// inside app/config/file.php
80 | 'areas' => array(
81 | 'my_area' => array(
82 | 'basedir' => DOCROOT.'uploads',
83 | 'use_locks' => true,
84 | ),
85 | ),
86 |
87 | // Now get the area
88 |
89 | $area = \File::instance('my_area');
90 |
91 |
92 |
95 | There are 2 ways to use areas in the File class.
96 | The first is to use areas in a static context, supply a File_Area instance or identifier to the
97 | function you're calling.
98 |
// Read the contents of a directory
101 | try
102 | {
103 | $dir = File::read_dir('somedir', 0, null, 'my_area');
104 | }
105 | catch(\FileAccessException $e)
106 | {
107 | // Operation failed
108 | }
109 |
110 |
111 | The second way is to call the functions directly from the area itself.
112 | 113 |// Get the area
114 | $area = File::instance('my_area');
115 |
116 | try
117 | {
118 | $dir = $area->read_dir('somedir', 0, null);
119 | }
120 | catch(\FileAccessException $e)
121 | {
122 | // Operation failed
123 | }
124 |
125 |
126 | 132 | Read about File Handlers. 133 |
134 |40 | The Mongo_Db class provides methods to interact with 41 | Mongo databases. 42 |
43 |44 | Besides providing the normal insert, select, delete and update functionality it has some management 45 | methods to help you with database utility operations. 46 |
47 | 48 |51 | For every Mongo database connection there must be a config in mongo array in app/config/db.php. 52 | Configuration options and explanation are listed below. Every config requires to contain a hostname 53 | and database name. 54 |
55 | 56 || Param | 60 |Type | 61 |Required | 62 |Description | 63 |
|---|---|---|---|
| hostname | 66 |string | 67 |yes | 68 |the TCP hostname, OR a UNIX socket filepath | 69 |
| database | 72 |string | 73 |yes | 74 |the database name | 75 |
| port | 78 |number | 79 |no | 80 |the port to use in the connection, OR 0 if the hostname is a UNIX socket | 81 |
| replicaset | 84 |string | 85 |no | 86 |the name of the replicaset to use for the connection | 87 |
| username | 90 |string | 91 |no | 92 |username used for authentication, ignored if no password has been set | 93 |
| password | 96 |string | 97 |no | 98 |password used for authentication, ignored if no password has been set | 99 |
Example config:
104 | 105 |// Inside app/config/db.php
106 |
107 | 'mongo' => array(
108 | // This group is used when no instance name has been provided.
109 | 'default' => array(
110 | 'hostname' => 'localhost',
111 | 'database' => 'mongo_fuel',
112 | ),
113 |
114 |
115 | // List your own groups below.
116 | 'my_mongo_connection' => array(
117 | 'hostname' => 'localhost',
118 | 'database' => 'my_db',
119 | 'replicaset' => 'replica',
120 | 'username' => 'user',
121 | 'password' => 'p@s$w0rD',
122 | ),
123 |
124 | // An alternative group example using a UNIX socket connection, instead of the TCP localhost
125 | 'my_mongo_sock' => array(
126 | 'hostname' => '/tmp/mongodb-27017.sock',
127 | 'port' => 0,
128 | 'database' => 'mongo_fuel',
129 | ),
130 |
131 | ),
132 |
133 |
134 | Once you have your setting in place you can start using MongoDB.
135 | 136 |137 | In order to use MongoDB this must be available on your server. To see if you have mongo 138 | support on you server, look for the Mongo section in your phpinfo() or ask you hosting company. 139 |
140 | 141 |The Auth package provides a standardized interface for authentication in Fuel. This allows our users to 38 | write their own drivers and easily integrate a new driver to work with old code by keeping the basic methods 39 | consistent.
40 | 41 |45 | Writing drivers can be done in two ways. Either by extending the Auth driver classes 46 | to create a new driver from scratch or extending a existing driver class and changing them where needed. 47 |
48 | 49 |50 | An Auth driver consists of three types of classes working together. These are: 51 |
52 | 53 | 58 | 59 |Extend these classes like so:
62 | 63 |<?php
64 |
65 | class Auth_Login_Mydriver extends \Auth\Auth_Login_Driver
66 | {
67 |
68 | // Implement all the needed functions and variables defined in the driver class.
69 |
70 | }
71 |
72 | /* End of file app/classes/auth/login/mydriver.php */
73 |
74 |
75 | 78 | When extending the Auth driver classes take note on the expected return values of each function that needs to be implemented. 79 | Every method supplies an example so you know what needs to be returned. Here is an example: 80 |
81 | 82 |/**
83 | * Get User Identifier of the current logged in user
84 | * in the form: array(driver_id, user_id)
85 | *
86 | * @return array
87 | */
88 | abstract public function get_user_id();
89 |
90 | 91 | The code above show you the get_user_id function that every driver should have. 92 | Like in all classes you extend that have abstract functions, these functions must be defined in the extended class. 93 | The return type of this function is provided in the comment, in this case array(driver_id, user_id). 94 | In order to get your driver to work alongside other drivers make sure you return the right values or your driver 95 | breaks protocol. 96 |
97 | 98 |99 | Here is that same function but then the implementation from the Simpleauth driver. 100 |
101 | 102 |/**
103 | * Get the user's ID
104 | *
105 | * @return Array containing this driver's ID & the user's ID
106 | */
107 | public function get_user_id()
108 | {
109 | if (empty($this->user))
110 | {
111 | return false;
112 | }
113 |
114 | return array($this->id, (int) $this->user['id']);
115 | }
116 |
117 |
118 | 119 | Once you have everything in place for the new driver, replace or add it to the auth config. 120 |
121 | 122 |// Inside config/auth.php array
123 |
124 | // Add it as a second driver
125 | 'driver' => array('Simpleauth', 'Mydriver'),
126 |
127 | // or replace the existing driver
128 | 'driver' => array('Mydriver'),
129 |
130 |
131 | 39 | When it comes to organizing, reuse and share your code, packages are a great way to allow you to do this. 40 | They can contain all sorts of code like models, third-party libraries, configs and so on. 41 | Packages also allow you to extend the core without messing up your app/classes directory. 42 | To clarify what packages are, here are the "is" and "is not" on packages. 43 |
44 | 45 |Installing packages can be done manually and through oil. To install manually download the package source and place it into your package directory (default in fuel/packages).
61 |To actually be able to use your it you must either add it to always_load in
62 | app/config/config.php or use Package::load().
To help people understand what you are doing it's best to structure your package like so:
66 | 67 |/packages
68 | /package
69 | /bootstrap.php
70 | /classes
71 | /your.php
72 | /classes.php
73 | /here.php
74 | /config
75 | /packageconfig.php
76 | /and_so_on
77 |
78 |
79 | 80 | Every package is expected to have a bootstrap.php located at the base of the package. 81 | Use the bootstrap to add the package namespace (to global if you wish). And add the classes for better perfomance. 82 |
83 | 84 |// Add namespace, necessary if you want the autoloader to be able to find classes
85 | Autoloader::add_namespace('Mypackage', __DIR__.'/classes/');
86 |
87 | // Add as core namespace
88 | Autoloader::add_core_namespace('Mypackage');
89 |
90 | // Add as core namespace (classes are aliased to global, thus useable without namespace prefix)
91 | // Set the second argument to true to prefix and be able to overwrite core classes
92 | Autoloader::add_core_namespace('Mypackage', true);
93 |
94 | // And add the classes, this is useful for:
95 | // - optimization: no path searching is necessary
96 | // - it's required to be able to use as a core namespace
97 | // - if you want to break the autoloader's path search rules
98 | Autoloader::add_classes(array(
99 | 'Mypackage\\Classname' => __DIR__.'/classes/classname.php',
100 | 'Mypackage\\Anotherclass' => __DIR__.'/classes/anotherclass.php',
101 | ));
102 |
103 |
104 | Once you have your classes in place you can now start using them.
105 | 106 |Note: if package namespaces aren't aliased to global you must supply it:
107 | 108 |// If aliased to global just use
109 | $instance = new Myclass;
110 |
111 | // When not aliased to global
112 | $instance = new Mynamespace\Myclass;
113 |
114 |
115 | The application profiler bundled with FuelPHP is based on PHP Quick Profiler.
38 | 39 |42 | The profiler provides profiling and debugging related information without having to add a lot of programmatic overhead 43 | to the code. You only need to toggle one config setting to true and you have access to an automated tool to help create a 44 | faster and more consistent review experience. Since anyone can use it, the profiler also gives you an idea of where the code 45 | stands before the review. 46 |
47 | 48 |The profiler provides you with a tabbed interface, in which you can find the following information:
49 |A typical profiler screen looks like this:
At the bottom of the profiler screen, you will find three options:
64 |73 | Profiling your application is disabled by default. You can configure Fuel to activate the profiler via your applications config/config.php file. 74 |
75 |'profiling' => true,
76 |
77 | 78 | After the profiler has been enabled, you will see it pop up at the bottom of your browser window. 79 |
80 | 81 |84 | Database profiling is disabled by default too. Database profiling is activated per defined database, and is 85 | activated by setting the 'profiling' option of the database configuration you want to profile in your 86 | config/<environment>/db.php to true. 87 |
88 | 89 |'profiling' => true,
90 |
91 | If you use multiple environments, make sure to select the correct db.php configuration file.
92 | 93 |See the documentation of the Profiler class to see how you can interact with the profiler.
96 | 97 |43 | The File class offers a set of methods for working with files & directories. This can 44 | be done through some helper methods or through a more advanced object oriented method where 45 | all files and directories are wrapped in objects. 46 |
47 | 48 |54 | The File class is highly configurable and gives you all the control you need over the behaviour 55 | supplied by the class. Configuration settings vary from restricting filesystem access to setting 56 | drivers by filetype. 57 |
58 | 59 |60 | The default file config is located at core/config/file.php. To change these settings 61 | create a config file with your own settings at app/config/file.php. 62 |
63 | 64 |65 | The following configuration values can be defined: 66 |
67 | 68 || Param | 72 |Type | 73 |Default | 74 |Description | 75 |
|---|---|---|---|
| base_config.basedir | 78 |string | 79 | |
80 | 81 | The path to the basedir. Defaults to null for no restrictions. 82 | When defined this will restrict the access to that specific directory. 83 | | 84 |
| base_config.extensions | 87 |array | 88 | |
89 | 90 | Array of allowed extensions, null for all. 91 | If defined the File class will only handle the given extentions and 92 | filter out the rest. 93 | | 94 |
| base_config.url | 97 |string | 98 | |
99 | 100 | Base url for files, null for not available. 101 | | 102 |
| base_config.use_locks | 105 |null | 106 | |
107 | 108 | Whether to use file locks. Set to true if you want the File class to use them. 109 | | 110 |
| base_config.file_handlers | 113 |array | 114 | |
115 | 116 | Array of file drivers per extension. These allow you to use custom drivers on a by filetype basis. 117 | | 118 |
| magic_file | 121 |string | 122 | |
123 | 124 | Alternative location of the fileinfo() magic file. If not specified, the system default will be used. 125 | | 126 |
| chmod.files | 129 |integer | 130 | |
131 | 132 | Permissions for newly created files. 133 | | 134 |
| chmod.folders | 137 |integer | 138 | |
139 | 140 | Permissions for newly created directories. 141 | | 142 |
40 | The Theme class provides theming to your application. 41 |
42 | 43 |46 | Every Theme class instance has its own instance of the Asset class, to make it easy to load assets from the theme. 47 | The Asset instance is populated with the asset paths of both the active and the fallback theme, which will provide 48 | the same fallback features for your assets as you have for other theme elements like templates and views. 49 |
50 | 51 |Example:
52 | 53 |// load an asset using the default theme instance
54 | echo \Theme::instance()->asset->css('bootstrap.css');
55 |
56 | 59 | The methods active(), fallback(), 60 | get_info() and load_info() by default allow you 61 | to pass a string with the name of an installed theme. 62 | These methods allow you to pass an theme definition array instead, which makes it possible to pass extra configuration information. 63 |
64 | 65 |The following theme variables are defined:
66 | 67 || Param | 71 |Type | 72 |Default | 73 |Description | 74 |
|---|---|---|---|
| name | 77 |string | 78 |required | 79 |The name of the theme. This must match to a folder in the path specified. | 80 |
| path | 83 |string | 84 |required | 85 |The path of the theme. This must include the name of the theme, and end with a directory separator. | 86 |
| asset_base | 89 |string | 90 |optional | 91 |92 | The base path to the assets of this theme, relative to the application DOCROOT. 93 | If outside the DOCROOT, the path should be fully qualified. 94 | It should end with a directory separator. 95 | If not specified, it will be constructed from the given theme path, the configured assets_folder, 96 | and the configured base_url. 97 | | 98 |
| info | 101 |array | 102 |optional | 103 |The theme's information array. If not defined, it will be created from the information in the theme info file. | 104 |
| find_file | 107 |boolean | 108 |optional | 109 |If set to true, the Finder::search() method will be used to locate view files and theme info files. | 110 |
Example:
115 | 116 |// standard usage: create an instance and set the active theme
117 | $theme = \Theme::forge();
118 | $theme->active('darkglow');
119 |
120 | // advanced usage
121 | \Config::load('theme', true, false, true);
122 | $config = \Config::get('theme', false);
123 |
124 | // override a config value
125 | $config['info_file_name'] = 'setupinfo.yaml';
126 |
127 | // create the theme instance
128 | $theme = \Theme::forge($config);
129 |
130 | // set the active theme
131 | $theme->active(
132 | array(
133 | 'name' => 'darkglow',
134 | 'path' => APPPATH.'themes'.DS.'darkglow'.DS,
135 | 'asset_base' => '/themes/darkglow/assets/',
136 | 'find_file' => true,
137 | )
138 | );
139 |
140 |
141 | 40 | The Crypt class allows encrypt or decrypt a string. The Crypt class is also used internally by for example the Fuel Sessions class. 41 |
42 |43 | Until version 1.8, Crypt used the encryption and hashing methods provided by the composer package PHPSecLib. 44 | Currently, it uses Sodium, either internally in PHP 7.2+, using libsodium if available, or via software emulation through the sodium-compat composer package. 45 | It's not dependent on external PHP modules being available, such as mcrypt. 46 |
47 |48 | Crypt encryption is backwards compatible. If you have data encrypted with PHPSeclib, it will detect this from the encrypted data, and decrypt using PHPSeclib using the old crypt keys. 49 | When encrypting data, it will always use Sodium. 50 |
51 | 52 |56 | The Crypt class is configured through the app/config/crypt.php configuration file. It will be generated and populated with random values when you first use the Crypt class or if one of the required configuration values is missing. 57 |
58 |59 | Note that this will require write access to app/config/crypt.php! If this is not possible, Crypt terminates with an error, while displaying the contents that should be written to the config file. You need to copy and paste this into the file yourself before you can continue. 60 |
61 |The following configuration settings can be defined:
62 || Param | 66 |Type | 67 |Default | 68 |Description | 69 |
|---|---|---|---|
| legacy.crypto_key | 72 |string | 73 |n/a | 74 |75 | PHPSecLib: Random string used as encryption key in the encryption routines. Make sure you set this to something unique and random! 76 | | 77 |
| legacy.crypto_iv | 80 |string | 81 |n/a | 82 |83 | PHPSecLib: Random string used as encryption initialisation vector in the encryption routines. Make sure you set this to something unique and random! 84 | | 85 |
| legacy.crypto_hmac | 88 |string | 89 |n/a | 90 |91 | PHPSecLib: Random string used in the Hash-based Message Authentication Code (HMAC) routines. Make sure you set this to something unique and random! 92 | | 93 |
| sodium.cipherkey | 96 |string | 97 |n/a | 98 |99 | Sodium: Random hexadecimal value used in the Hash-based Message Authentication Code (HMAC) routines. Make sure you set this to something unique and random! 100 | | 101 |
107 | If you want to assign the legacy keys manually, make sure they are base64_encoded using the safe_b64encode() method from the Crypt class, and have a string length that is a multiple of 4! 108 |
109 |110 | If you want to assign the cipherkey, use sodium_bin2hex(random_bytes(SODIUM_CRYPTO_STREAM_KEYBYTES))) to create a sufficiently random key in the correct format! 111 |
112 | 113 |114 | If you have a crypt configuration file with legacy keys from a pre-1.8.1 version of the framework, it will automatically be converted to the new format, and a cipherkey is randomly generated, upon first use of the new Sodium powered Crypt class. 115 |
116 |Orm is short for Object
39 | Relational Mapper which does 2 things: it maps your database table rows to objects and it allows you
40 | to establish relations between those objects.
41 | It follows closely the
42 | Active Record Pattern, but was also influenced by other systems.
You can add any class as an observer by adding the full classname (namespace included) to the Observers 48 | property of your model. There's 2 ways of creating classes that can be used as observers:
49 | 50 |Create a new class that extends Orm\Observer and create methods for the events upon which you 53 | want your Observer to act. In the example below you want it to act upon after_insert. The 54 | method will be passed the Model instance it is acting upon.
55 | 56 |class Observer_Something extends Orm\Observer
57 | {
58 |
59 | public function after_insert(Orm\Model $model)
60 | {
61 | \Log::info('Succesfully created new object of class '.get_class($model));
62 | }
63 | }
64 |
65 | Extensions of the type Orm\Observer are singletons by default, as such you can't use a 66 | method instance() or property $_instance or it won't work anymore. Because of this 67 | methods may be both static or non-static.
68 | 69 |When you extend the Orm\Observer class it inherits an orm_notify() method that 72 | will check if there's a method that matches the event and call it when possible. But you can use any 73 | class as an observer as long as it has an orm_notify() method. That will be called on events 74 | and be passed the event name and a Model instance.
75 | 76 |class Some_Other_Class
77 | {
78 |
79 | // it may have many methods and properties before or after the orm_notify method
80 |
81 | public static function orm_notify(Orm\Model $model, $event)
82 | {
83 | \Log::info('I was notified of the event '.$event.' on a Model of class '.get_class($model));
84 | }
85 | }
86 | 103 | before_insert and before_update are triggered only if the object has been changed. If you need to trigger an event even if the object has not been changed (ex.: to handle $_FILES datas), you should use before_save. 104 |
105 | 106 |40 | The Crypt class allows encrypt or decrypt a string. The Crypt class is also used internally by for example the Fuel Sessions class. 41 |
42 |It uses the encryption and hashing methods provided by PHPSecLib, so it's not dependent on external modules being available, such as mcrypt.
43 | 44 |48 | Using crypt can be done in 2 ways: through static usage of the Crypt class and through crypt objects 49 | returned by the Crypt::forge() or Crypt::instance() methods. This section covers static usage which will always work 50 | with the default instance using the configuration specified in the configuration. 51 |
52 | 53 |54 | Using crypt objects, Crypt::instance() and Crypt::forge() is explained in the advanced section. 55 |
56 | 57 |The encode method encrypts a string value, optionally with a custom encryption key.
60 || Static | 64 |No | 65 ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Parameters | 68 |
69 |
|
87 | |||||||||
| Returns | 90 |string | 91 ||||||||||
| Example | 94 |
95 |
97 | |
98 |
The decode method decrypts a string value, optionally with a custom key.
106 || Static | 110 |No | 111 ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Parameters | 114 |
115 |
|
133 | |||||||||
| Returns | 136 |mixed - String value with the decoded value, or false if the value could not be decoded. | 137 ||||||||||
| Example | 140 |
141 |
143 | |
144 |
Fuel is now at v1.8.1. You can download Fuel using the links below:
39 | 40 |To install one of the Fuel approved packages from the commandline, use the Oil utility.
89 | 90 |Fuel is developed using a community approach and we encourage participation. If you are interested in 93 | contributing, please take a second to read our Coding 94 | Standards. Any contributions that do not meet these guidelines will not be accepted. Otherwise: 95 | fork, commit & make pull-request. If you don't know how: 96 | http://help.github.com/forking/ 97 |
98 | 99 |102 | Do you have something that might be of interest to other Fuel users? Create a package. 103 | If it's properly coded, and it complies with our Coding Standards, we can publish it on 104 | this page and make it available for installation through the oil commandline utility. 105 |
106 | 107 |The Parser package extends the Core View class to be able to use any type of template parser you want.
38 | 39 |The Parser package changes nothing about the way you work with Views, but it will allow you to 43 | use any template parser you want instead of PHP. The package comes with many drivers for parsers like 44 | Dwoo, Haml, Jade, Lex, Markdown, Mustache, PHPTal, Smarty and Twig.
45 | 46 |Which parser is used is determined by the file extension of your view file. Normal views, parsed by PHP 47 | use the file extension .php. This is also the default, if no extension is specified, it is 48 | assumed to have the .php extension.
49 |All others have their own specific extension, for example foo.mustache will use the Mustache 50 | driver, foo.tpl will use the Dwoo driver, foo.lex will use the Lex driver, and 51 | so on. The default extension can be changed in config).
52 | 53 |The Parser package is included in the Fuel download. To use it you must first enable it by adding 57 | it to your config:
58 |'always_load' => array(
59 | 'packages' => array(
60 | 'parser',
61 | ),
62 | ),
63 | To be able to use one of the supported parsers, you need to install them via composer. 64 | Simply add the libraries to your project's composer.json then run php composer.phar install:
65 | 66 |{
67 | "require": {
68 | "dwoo/dwoo" : "*",
69 | "mustache/mustache" : "*",
70 | "smarty/smarty" : "*",
71 | "twig/twig" : "*",
72 | "mthaml/mthaml": "*",
73 | "8ctopus/lex": "*"
74 | }
75 | }
76 |
77 |
78 | Note that the Markdown parser is installed by default, as it is also used by the FuelPHP core class Markdown.
79 | 80 |Libraries that can not be installed through composer are expected to be installed in APPPATH/vendor/lib_name 81 | (capitalize lib_name), and you'll have to download them yourself. Don't change the casing or anything, keep it as 82 | much original as possible within the vendor/lib_name dir to keep updating easy (also because some come with 83 | their own autoloader).
84 |Parser can be configured in a config/parser.php file and takes the following keys:
90 | 91 || Param | 95 |Type | 96 |Default | 97 |Description | 98 |
|---|---|---|---|
| extensions | 101 |array | 102 |(array with extensions and View class which parses them) | 103 |
104 | Defines which extensions are valid and what their View driver is. 105 | ex: 'md' => 'View_Markdown' 106 | |
107 |
For every View driver supported, the configuration file contains a array entry with 111 | the same name as the driver, which lists the driver specific configuration (limited 112 | to the configuration items supported by the driver. This may be a subset of all 113 | configuration the parser supports).
114 |All drivers have a parser() method that will allow you to access the current 120 | Parser object. This is a convention and not a requirement and might be different on 3rd party 121 | drivers.
122 | 123 |// Clear the cache for a specific Smarty template
124 | $view = View::forge('example.smarty');
125 | $view->parser()->clearCache('example.smarty');
126 |
127 | // Example static usage
128 | View_Smarty::parser()->clearCache('example.smarty');
129 |
130 | This can also be used when you need to pass custom configuration to the driver.
131 |40 | (extends Query_Builder_Where) 41 |
42 | 43 |44 | The Query_Builder_Delete class handles all the delete operations for the query building process. It extends the 45 | Query_Builder_Where class, so all the methods are inherited. 46 |
47 | 48 |The table method sets/changes the table to delete from.
51 || Static | 55 |No | 56 |||||||||
|---|---|---|---|---|---|---|---|---|---|
| Parameters | 59 |
60 |
|
75 | ||||||||
| Returns | 78 |Returns the current instance. | 79 |||||||||
| Example | 82 |
83 |
91 | |
92 |
The compile method returns the delete SQL query as a string.
100 || Static | 104 |No | 105 |||||||||
|---|---|---|---|---|---|---|---|---|---|
| Parameters | 108 |
109 |
|
124 | ||||||||
| Returns | 127 |Returns the SQL query as a string. | 128 |||||||||
| Example | 131 |
132 |
146 | |
147 |
The reset method resets all values of the current instance.
155 || Static | 159 |No | 160 |
|---|---|
| Parameters | 163 |164 | None 165 | | 166 |
| Returns | 169 |Returns the current instance. | 170 |
| Example | 173 |
174 |
194 | |
195 |
The Package class allows you to easily load, unload, check if a package is loaded, or get all packages loaded.
40 | 41 |The load method allows you to load one or more packages at runtime. If the package cannot be found a PackageNotFoundException will be thrown.
44 || Static | 48 |Yes | 49 ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Parameters | 52 |
53 |
|
71 | |||||||||
| Returns | 74 |void | 75 ||||||||||
| Example | 78 |
79 |
91 | |
92 |
The unload method allows you to unload a package at runtime.
100 || Static | 104 |Yes | 105 |||||||
|---|---|---|---|---|---|---|---|
| Parameters | 108 |
109 |
|
122 | ||||||
| Returns | 125 |void | 126 |||||||
| Example | 129 |
130 |
133 | |
134 |
The loaded method allows you to check if a package is currently loaded. If no package name is given then all loaded packages are returned.
142 || Static | 146 |Yes | 147 |||||||
|---|---|---|---|---|---|---|---|
| Parameters | 150 |
151 |
|
164 | ||||||
| Returns | 167 |bool|array | 168 |||||||
| Example | 171 |
172 |
185 | |
186 |
40 | The Crypt class allows encrypt or decrypt a string. The Crypt class is also used internally by for example the Fuel Sessions class. 41 |
42 |It uses the encryption and hashing methods provided by PHPSecLib, so it's not dependent on external modules being available, such as mcrypt.
43 | 44 |48 | The Crypt class supports the use of multiple instances. This might prove useful if you require multiple encryption 49 | key sets. 50 |
51 |52 | You can use the same methods on an crypt instance as you would when you the static methods. For the method 53 | definition see the class usage page. 54 |
55 | 56 |59 | The forge method allows you to manually instantiate a crypt instance. 60 |
61 || Static | 65 |Yes | 66 ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Parameters | 69 |
70 |
|
96 | |||||||||
| Returns | 99 |object - The instantiated crypt object. | 100 ||||||||||
| Example | 103 |
104 |
111 | |
112 |
120 | The instance method allows you load a named instance of the crypt class. 121 |
122 || Static | 126 |Yes | 127 |||||||
|---|---|---|---|---|---|---|---|
| Parameters | 130 |
131 |
|
147 | ||||||
| Returns | 150 |mixed - The named crypt instance or false if the instance does not exist. | 151 |||||||
| Example | 154 |
155 |
160 | |
161 |
167 | The static methods of the Crypt class will also use the default instance. Remember this if you 168 | alter the configuration of the default instance! 169 |
170 | 171 |The cache class allows you to cache the result of a resource heavy operation.
40 | 41 |The cache class's defaults are configured through the fuel/core/config/cache.php configuration file. It 45 | is already populated with a default configuration. You can override this configuration adding a config file 46 | with the same name to your application config directory, and set the values you want to change there. These 47 | will overwrite the core config but keep what you didn't overwrite.
48 | 49 |The following global configuration values can be defined:
50 || Param | 54 |Type | 55 |Default | 56 |Description | 57 |
|---|---|---|---|
| driver | 60 |string | 61 | |
62 | 63 | The default storage driver used for saving the caches. 64 | | 65 |
| expiration | 68 |int | 69 | |
70 | 71 | The default number of seconds until expiration, used when no lifetime is given. When set to 72 | null it won't expire. 73 | | 74 |
| (type)_handler | 77 |string | 78 | |
79 |
80 | When caching strings nothing special happens unless when caching more complex things like
81 | objects, or even more primitive like doubles. For those cases there are "content handlers"
82 | included which can ensure you'll get your object back as the right kind of object. By
83 | default handlers are included for using PHP serialization and JSON encoding. 84 | You can add your own or handle different kinds of objects/primitive types in different ways 85 | by adding handlers for each of them: 'int_handler' => 'json', 'string_handler' => 'string', 86 | 'Model_Post' => 'serialize', etc... 87 | |
88 |
For each of the cache storage drivers, a separate configuration section exists. This section contains 93 | the driver specific parameters.
94 | 95 |Saves the caches to the filesystem.
99 | 100 |Specific driver configuration:
101 || Param | 105 |Type | 106 |Default | 107 |Description | 108 |
|---|---|---|---|
| path | 111 |string | 112 | |
113 | Basepath for saving the caches. | 114 |
Specific driver configuration:
123 || Param | 127 |Type | 128 |Default | 129 |Description | 130 |
|---|---|---|---|
| cache_id | 133 |string | 134 | |
135 | Unique id to distinguish fuel cache items from others stored on the same server(s). | 136 |
| servers | 139 |string | 140 | |
143 | Array of servers and portnumbers that run the memcached service. | 144 |
Specific driver configuration:
153 || Param | 157 |Type | 158 |Default | 159 |Description | 160 |
|---|---|---|---|
| database | 163 |string | 164 | |
165 | Name of the redis database to use (as configured in config/db.php) | 166 |
41 | Whenever data needs to be retrieved, manipulated or deleted this should always be done by a model. A Model is a representation of some kind of 42 | data and has the methods to change them. For example: you never put SQL queries in a Controller, those are put in the Model and the Controller will 43 | call upon the Model to execute the queries. This way if your database changes you won't need to change all your Controllers but just the Model that acts upon it. 44 |
45 | 46 |49 | In Fuel a Model is essentially just a Class like any other. They do nothing more than a library, but the Model_ prefix 50 | helps to differentiate it from other classes. To do something useful with a Model you will need to use other classes. 51 |
52 | 53 |
56 | namespace Model;
57 |
58 | class Welcome extends \Model {
59 |
60 | public static function get_results()
61 | {
62 | // Database interactions
63 | }
64 |
65 | }
66 |
67 | Remember to prefix a backslash to classes you're using from global, outside the namespace 68 | you're in. If you don't understand why, read up on namespaces on 69 | PHP.net.
70 | 71 |PHP has the use keyword for importing classes into the current namespace, this allows
74 | you to shorten the Model's classname from Model\Welcome to just Welcome
75 | within the file of a specific class:
78 | use \Model\Welcome;
79 |
80 | class Controller_Welcome extends Controller
81 | {
82 | public function action_index()
83 | {
84 | $results = Welcome::get_results();
85 | }
86 | }
87 |
88 |
89 |
90 | While models can be used with any type of data storage we'll focus here on usage with SQL because that's the 93 | most common usage. Almost always your models will have at least all CRUD 94 | methods: create, read, update, delete (or variations on those). In Fuel your models don't need to extend 95 | anything by default, though you can of course create your own base model or use Fuel's 96 | Orm package.
97 | 98 |You can use the DB class to build queries with native SQL like so:
101 | 102 |DB::query('SELECT * FROM users WHERE id = 5');
103 |
104 | When it comes to escaping data, working with data in arrays or making an application portable over multiple database engines, you might find native 107 | SQL to be rather cumbersome. Using the Query Builder methods in the DB Class you can abstract writing native SQL: 108 |
109 | 110 |DB::select('title','content')->from('articles')->execute()->get('title');
111 |
112 | See more about native SQL queries and using the Query Builder in the DB class documentation.
113 | 114 |One possible way of creating models is by using Model_Crud, which adds a commonly used functionality to your models for interacting with a database table. There's an example of its usage below.
117 | 118 |// find all articles
119 | $entry = Model_Article::find_all();
120 |
121 | // find all articles from category 1 order descending by date
122 | $entry = Model_Article::find(array(
123 | 'where' => array('category_id', 1),
124 | 'order_by' => array('date' => 'desc')
125 | ));
126 |
127 | For models with more functionality, like support for relations, you can use the Orm Package, which adds a lot of functionality out-of-the-box to your models. There's an example of its usage below.
130 | 131 |// find all articles
132 | $entry = Model_Article::find('all');
133 |
134 | // find all articles from category 1 order descending by date
135 | $entry = Model_Article::find('all', array(
136 | 'where' => array('category_id', 1),
137 | 'order_by' => array('date', 'desc')
138 | ));
139 |
140 | Model_Crud and the ORM package use similar syntax, which makes it simple to migrate once you require more functionality than Model_Crud can provide.
141 | 142 |A Template Controller is an extension of the Base Controller which has template support built in using some pre-defined before() and after() methods. Basically it can be used to wrap 41 | your view in a layout with a header, footer, sidebar, etc.
42 | 43 |Like all Controllers you create a class in the fuel/app/classes/controller directory. They need to extend the Controller_Template class and are prefixed by default by "Controller_". Below is an example of the controller "example":
46 | 47 |Please note: by default, all methods of a class that extends Controller_Template will use the template.
48 |
However, it is possible to omit methods from the template.
class Controller_Example extends Controller_Template
51 | {
52 | public function action_index()
53 | {
54 | $data = array();
55 | $this->template->title = 'Example Page';
56 | $this->template->content = View::forge('test/index', $data);
57 | }
58 | }
59 |
60 | Please note: if you have a before() method in your template controller extension you 63 | must add parent::before(); to that method or the $this->template will 64 | not be available. Make after() compatible with that of the Controller_Template: 65 | use after($response) instead of just after().
66 | 67 | 68 |class Controller_Example extends Controller_Template
69 | {
70 | /**
71 | * Your before method
72 | */
73 | public function before()
74 | {
75 | parent::before(); // Without this line, templating won't work!
76 |
77 | // do stuff
78 | }
79 |
80 | /**
81 | * Make after() compatible with Controller_Template by adding $response as a parameter
82 | */
83 | public function after($response)
84 | {
85 | $response = parent::after($response); // not needed if you create your own response object
86 |
87 | // do stuff
88 |
89 | return $response; // make sure after() returns the response object
90 | }
91 |
92 | public function action_index()
93 | {
94 | $data = array();
95 | $this->template->title = 'Example Page';
96 | $this->template->content = View::forge('test/index', $data);
97 | }
98 | }
99 |
100 | 103 | The template file is a great place to call up your JS, CSS, etc, structure your HTML and call view partials. It allows you to give your output 104 | structure. It is just a view file, by default the Template Controller will look here: fuel/app/views/template.php. 105 |
106 | 107 |<!DOCTYPE html>
108 | <html>
109 | <head>
110 | <meta charset="utf-8">
111 | <title><?php echo $title; ?></title>
112 |
113 | <?php echo Asset::css('main.css'); ?>
114 | </head>
115 | <body>
116 | <div id="wrapper">
117 | <h1><?php echo $title; ?></h1>
118 |
119 | <div id="content">
120 | <?php echo $content; ?>
121 | </div>
122 | </div>
123 | </body>
124 | </html>
125 |
126 |
129 | You can easily change the default APPPATH/views/template.php file to something different.
130 | You must set the public variable $template (note: you don't need .php extension here) to something different, example:
131 |
class Controller_Example extends Controller_Template
134 | {
135 |
136 | public $template = 'template_admin';
137 |
138 | public function action_index()
139 | {
140 | $this->template->title = 'Example Page';
141 | $this->template->content = View::forge('test/index', $data);
142 | }
143 | }
144 |
145 |
148 | By default, all methods of a class that extends Controller_Template will use the template.
149 | If you want to omit methods from the template, you can do this by returning something else in a
150 | Response object. That will overwrite the default template output.
151 |
class Controller_Example extends Controller_Template
154 | {
155 | public $template = 'template_admin';
156 |
157 | public function action_index()
158 | {
159 | $this->template->title = 'Example Page';
160 | $this->template->content = View::forge('test/index', $data);
161 |
162 | // this will show content in template
163 | }
164 |
165 | public function action_example()
166 | {
167 | $data['title'] = "Example Page";
168 | $data['content'] = "Don't show me in the template";
169 |
170 | // returned Response object takes precedence and will show content without template
171 | return new Response(View::forge('index/test', $data));
172 | }
173 | }
174 |
175 |
39 | Please note:
40 | • All information on this page is provided by third parties, not affiliated with the FuelPHP project.
41 | • The FuelPHP development team wasn't involved in writing any of these articles, tutorials, books or implementations.
Their contents can not be guaranteed to be accurate.
42 | • If the version discussed is different from the version you use, make sure you understand the differences between them.
43 | • Please ensure the quality and the contents meets with your requirements and expectations before using any of them.
44 |
FuelPHP is developed using a community approach and we encourage participation. If you are have information 96 | to share about FuelPHP, let us know, or fork the docs repository on Github, commit & make pull-request. 97 |
98 |99 | If you don't know how: http://help.github.com/forking/. 100 |
101 | 102 |