diff options
author | Kyle Farris <kylefarris@kylefarris.gotdns.org> | 2011-10-14 18:48:53 +0200 |
---|---|---|
committer | Kyle Farris <kylefarris@kylefarris.gotdns.org> | 2011-10-14 18:48:53 +0200 |
commit | 974cc5757e1da3a89af7b9bc700b805ba05dd3bb (patch) | |
tree | 109313ba07a2eed2bb8d015ef5f6af8f9205dae2 /user_guide_src/source/general | |
parent | 6636cef6fc457b3a0490d051587cb430aa0021d0 (diff) | |
parent | a2125a5d830fd390b4cf35f77e9bb0558cfa2dd7 (diff) |
Merged with develop and updated to new changelog.
Diffstat (limited to 'user_guide_src/source/general')
29 files changed, 3169 insertions, 0 deletions
diff --git a/user_guide_src/source/general/alternative_php.rst b/user_guide_src/source/general/alternative_php.rst new file mode 100644 index 000000000..4dc857a50 --- /dev/null +++ b/user_guide_src/source/general/alternative_php.rst @@ -0,0 +1,76 @@ +################################### +Alternate PHP Syntax for View Files +################################### + +If you do not utilize CodeIgniter's :doc:`template +engine <../libraries/parser>`, you'll be using pure PHP in your +View files. To minimize the PHP code in these files, and to make it +easier to identify the code blocks it is recommended that you use PHPs +alternative syntax for control structures and short tag echo statements. +If you are not familiar with this syntax, it allows you to eliminate the +braces from your code, and eliminate "echo" statements. + +Automatic Short Tag Support +=========================== + +.. note:: If you find that the syntax described in this page does not + work on your server it might be that "short tags" are disabled in your + PHP ini file. CodeIgniter will optionally rewrite short tags on-the-fly, + allowing you to use that syntax even if your server doesn't support it. + This feature can be enabled in your config/config.php file. + +Please note that if you do use this feature, if PHP errors are +encountered in your **view files**, the error message and line number +will not be accurately shown. Instead, all errors will be shown as +eval() errors. + +Alternative Echos +================= + +Normally to echo, or print out a variable you would do this:: + + <?php echo $variable; ?> + +With the alternative syntax you can instead do it this way:: + + <?=$variable?> + +Alternative Control Structures +============================== + +Controls structures, like if, for, foreach, and while can be written in +a simplified format as well. Here is an example using foreach:: + + <ul> + + <?php foreach ($todo as $item): ?> + + <li><?=$item?></li> + + <?php endforeach; ?> + + </ul> + +Notice that there are no braces. Instead, the end brace is replaced with +``endforeach``. Each of the control structures listed above has a similar +closing syntax: ``endif``, ``endfor``, ``endforeach``, and ``endwhile`` + +Also notice that instead of using a semicolon after each structure +(except the last one), there is a colon. This is important! + +Here is another example, using ``if``/``elseif``/``else``. Notice the colons:: + + <?php if ($username == 'sally'): ?> + + <h3>Hi Sally</h3> + + <?php elseif ($username == 'joe'): ?> + + <h3>Hi Joe</h3> + + <?php else: ?> + + <h3>Hi unknown user</h3> + + <?php endif; ?> + diff --git a/user_guide_src/source/general/ancillary_classes.rst b/user_guide_src/source/general/ancillary_classes.rst new file mode 100644 index 000000000..f7c87011b --- /dev/null +++ b/user_guide_src/source/general/ancillary_classes.rst @@ -0,0 +1,49 @@ +########################## +Creating Ancillary Classes +########################## + +In some cases you may want to develop classes that exist apart from your +controllers but have the ability to utilize all of CodeIgniter's +resources. This is easily possible as you'll see. + +get_instance() +=============== + +**Any class that you instantiate within your controller functions can +access CodeIgniter's native resources** simply by using the +get_instance() function. This function returns the main CodeIgniter +object. + +Normally, to call any of the available CodeIgniter functions requires +you to use the $this construct:: + + $this->load->helper('url'); + $this->load->library('session'); + $this->config->item('base_url'); + // etc. + +$this, however, only works within your controllers, your models, or your +views. If you would like to use CodeIgniter's classes from within your +own custom classes you can do so as follows: + +First, assign the CodeIgniter object to a variable:: + + $CI =& get_instance(); + +Once you've assigned the object to a variable, you'll use that variable +*instead* of $this:: + + $CI =& get_instance(); + + $CI->load->helper('url'); + $CI->load->library('session'); + $CI->config->item('base_url'); + // etc. + +.. note:: You'll notice that the above get_instance() function is being + passed by reference:: + + $CI =& get_instance(); + + This is very important. Assigning by reference allows you to use the + original CodeIgniter object rather than creating a copy of it. diff --git a/user_guide_src/source/general/autoloader.rst b/user_guide_src/source/general/autoloader.rst new file mode 100644 index 000000000..259a4987e --- /dev/null +++ b/user_guide_src/source/general/autoloader.rst @@ -0,0 +1,23 @@ +###################### +Auto-loading Resources +###################### + +CodeIgniter comes with an "Auto-load" feature that permits libraries, +helpers, and models to be initialized automatically every time the +system runs. If you need certain resources globally throughout your +application you should consider auto-loading them for convenience. + +The following items can be loaded automatically: + +- Core classes found in the "libraries" folder +- Helper files found in the "helpers" folder +- Custom config files found in the "config" folder +- Language files found in the "system/language" folder +- Models found in the "models" folder + +To autoload resources, open the application/config/autoload.php file and +add the item you want loaded to the autoload array. You'll find +instructions in that file corresponding to each type of item. + +.. note:: Do not include the file extension (.php) when adding items to + the autoload array. diff --git a/user_guide_src/source/general/caching.rst b/user_guide_src/source/general/caching.rst new file mode 100644 index 000000000..bf6ed50f6 --- /dev/null +++ b/user_guide_src/source/general/caching.rst @@ -0,0 +1,58 @@ +################ +Web Page Caching +################ + +CodeIgniter lets you cache your pages in order to achieve maximum +performance. + +Although CodeIgniter is quite fast, the amount of dynamic information +you display in your pages will correlate directly to the server +resources, memory, and processing cycles utilized, which affect your +page load speeds. By caching your pages, since they are saved in their +fully rendered state, you can achieve performance that nears that of +static web pages. + +How Does Caching Work? +====================== + +Caching can be enabled on a per-page basis, and you can set the length +of time that a page should remain cached before being refreshed. When a +page is loaded for the first time, the cache file will be written to +your application/cache folder. On subsequent page loads the cache file +will be retrieved and sent to the requesting user's browser. If it has +expired, it will be deleted and refreshed before being sent to the +browser. + +Note: The Benchmark tag is not cached so you can still view your page +load speed when caching is enabled. + +Enabling Caching +================ + +To enable caching, put the following tag in any of your controller +functions:: + + $this->output->cache(n); + +Where n is the number of **minutes** you wish the page to remain cached +between refreshes. + +The above tag can go anywhere within a function. It is not affected by +the order that it appears, so place it wherever it seems most logical to +you. Once the tag is in place, your pages will begin being cached. + +.. important:: Because of the way CodeIgniter stores content for output, + caching will only work if you are generating display for your controller + with a :doc:`view <./views>`. + +.. note:: Before the cache files can be written you must set the file + permissions on your application/cache folder such that it is writable. + +Deleting Caches +=============== + +If you no longer wish to cache a file you can remove the caching tag and +it will no longer be refreshed when it expires. Note: Removing the tag +will not delete the cache immediately. It will have to expire normally. +If you need to remove it earlier you will need to manually delete it +from your cache folder. diff --git a/user_guide_src/source/general/cli.rst b/user_guide_src/source/general/cli.rst new file mode 100644 index 000000000..7dc1ca319 --- /dev/null +++ b/user_guide_src/source/general/cli.rst @@ -0,0 +1,78 @@ +################### +Running via the CLI +################### + +As well as calling an applications :doc:`Controllers <./controllers>` +via the URL in a browser they can also be loaded via the command-line +interface (CLI). + +.. contents:: Page Contents + +What is the CLI? +================ + +The command-line interface is a text-based method of interacting with +computers. For more information, check the `Wikipedia +article <http://en.wikipedia.org/wiki/Command-line_interface>`_. + +Why run via the command-line? +============================= + +There are many reasons for running CodeIgniter from the command-line, +but they are not always obvious. + +- Run your cron-jobs without needing to use wget or curl +- Make your cron-jobs inaccessible from being loaded in the URL by + checking for ``$this->input->is_cli_request()`` +- Make interactive "tasks" that can do things like set permissions, + prune cache folders, run backups, etc. +- Integrate with other applications in other languages. For example, a + random C++ script could call one command and run code in your models! + +Let's try it: Hello World! +========================== + +Let's create a simple controller so you can see it in action. Using your +text editor, create a file called tools.php, and put the following code +in it:: + + <?php + class Tools extends CI_Controller { + + public function message($to = 'World') + { + echo "Hello {$to}!".PHP_EOL; + } + } + ?> + +Then save the file to your application/controllers/ folder. + +Now normally you would visit the your site using a URL similar to this:: + + example.com/index.php/tools/message/to + +Instead, we are going to open Terminal in Mac/Lunix or go to Run > "cmd" +in Windows and navigate to our CodeIgniter project. + +.. code-block:: bash + + $ cd /path/to/project; + $ php index.php tools message + +If you did it right, you should see Hello World!. + +.. code-block:: bash + + $ php index.php tools message "John Smith" + +Here we are passing it a argument in the same way that URL parameters +work. "John Smith" is passed as a argument and output is: Hello John +Smith!. + +That's it! +========== + +That, in a nutshell, is all there is to know about controllers on the +command line. Remember that this is just a normal controller, so routing +and _remap works fine. diff --git a/user_guide_src/source/general/common_functions.rst b/user_guide_src/source/general/common_functions.rst new file mode 100644 index 000000000..70563b8d2 --- /dev/null +++ b/user_guide_src/source/general/common_functions.rst @@ -0,0 +1,81 @@ +################ +Common Functions +################ + +CodeIgniter uses a few functions for its operation that are globally +defined, and are available to you at any point. These do not require +loading any libraries or helpers. + +is_php('version_number') +========================== + +is_php() determines of the PHP version being used is greater than the +supplied version_number. + +:: + + if (is_php('5.3.0')) + { + $str = quoted_printable_encode($str); + } + +Returns boolean TRUE if the installed version of PHP is equal to or +greater than the supplied version number. Returns FALSE if the installed +version of PHP is lower than the supplied version number. + +is_really_writable('path/to/file') +==================================== + +is_writable() returns TRUE on Windows servers when you really can't +write to the file as the OS reports to PHP as FALSE only if the +read-only attribute is marked. This function determines if a file is +actually writable by attempting to write to it first. Generally only +recommended on platforms where this information may be unreliable. + +:: + + if (is_really_writable('file.txt')) + { + echo "I could write to this if I wanted to"; + } + else + { + echo "File is not writable"; + } + +config_item('item_key') +========================= + +The :doc:`Config library <../libraries/config>` is the preferred way of +accessing configuration information, however config_item() can be used +to retrieve single keys. See Config library documentation for more +information. + +show_error('message'), show_404('page'), log_message('level', 'message') +======================================================================== + +These are each outlined on the :doc:`Error Handling <errors>` page. + +set_status_header(code, 'text'); +================================ + +Permits you to manually set a server status header. Example:: + + set_status_header(401); + // Sets the header as: Unauthorized + +`See here <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>`_ for +a full list of headers. + +remove_invisible_characters($str) +=================================== + +This function prevents inserting null characters between ascii +characters, like Java\\0script. + +html_escape($mixed) +==================== + +This function provides short cut for htmlspecialchars() function. It +accepts string and array. To prevent Cross Site Scripting (XSS), it is +very useful. diff --git a/user_guide_src/source/general/controllers.rst b/user_guide_src/source/general/controllers.rst new file mode 100644 index 000000000..6e5079419 --- /dev/null +++ b/user_guide_src/source/general/controllers.rst @@ -0,0 +1,324 @@ +########### +Controllers +########### + +Controllers are the heart of your application, as they determine how +HTTP requests should be handled. + +.. contents:: Page Contents + +What is a Controller? +===================== + +**A Controller is simply a class file that is named in a way that can be +associated with a URI.** + +Consider this URI:: + + example.com/index.php/blog/ + +In the above example, CodeIgniter would attempt to find a controller +named blog.php and load it. + +**When a controller's name matches the first segment of a URI, it will +be loaded.** + +Let's try it: Hello World! +========================== + +Let's create a simple controller so you can see it in action. Using your +text editor, create a file called blog.php, and put the following code +in it:: + + <?php + class Blog extends CI_Controller { + + public function index() + { + echo 'Hello World!'; + } + } + ?> + +Then save the file to your application/controllers/ folder. + +Now visit the your site using a URL similar to this:: + + example.com/index.php/blog/ + +If you did it right, you should see Hello World!. + +Note: Class names must start with an uppercase letter. In other words, +this is valid:: + + <?php + class Blog extends CI_Controller { + + } + ?> + + +This is **not** valid:: + + <?php + class blog extends CI_Controller { + + } + ?> + +Also, always make sure your controller extends the parent controller +class so that it can inherit all its functions. + +Functions +========= + +In the above example the function name is index(). The "index" function +is always loaded by default if the **second segment** of the URI is +empty. Another way to show your "Hello World" message would be this:: + + example.com/index.php/blog/index/ + +**The second segment of the URI determines which function in the +controller gets called.** + +Let's try it. Add a new function to your controller:: + + <?php + class Blog extends CI_Controller { + + public function index() + { + echo 'Hello World!'; + } + + public function comments() + { + echo 'Look at this!'; + } + } + ?> + +Now load the following URL to see the comment function:: + + example.com/index.php/blog/comments/ + +You should see your new message. + +Passing URI Segments to your Functions +====================================== + +If your URI contains more then two segments they will be passed to your +function as parameters. + +For example, lets say you have a URI like this:: + + example.com/index.php/products/shoes/sandals/123 + +Your function will be passed URI segments 3 and 4 ("sandals" and "123"):: + + <?php + class Products extends CI_Controller { + + public function shoes($sandals, $id) + { + echo $sandals; + echo $id; + } + } + ?> + +.. important:: If you are using the :doc:`URI Routing <routing>` + feature, the segments passed to your function will be the re-routed + ones. + +Defining a Default Controller +============================= + +CodeIgniter can be told to load a default controller when a URI is not +present, as will be the case when only your site root URL is requested. +To specify a default controller, open your **application/config/routes.php** +file and set this variable:: + + $route['default_controller'] = 'Blog'; + +Where Blog is the name of the controller class you want used. If you now +load your main index.php file without specifying any URI segments you'll +see your Hello World message by default. + +Remapping Function Calls +======================== + +As noted above, the second segment of the URI typically determines which +function in the controller gets called. CodeIgniter permits you to +override this behavior through the use of the _remap() function:: + + public function _remap() + { + // Some code here... + } + +.. important:: If your controller contains a function named _remap(), + it will **always** get called regardless of what your URI contains. It + overrides the normal behavior in which the URI determines which function + is called, allowing you to define your own function routing rules. + +The overridden function call (typically the second segment of the URI) +will be passed as a parameter to the _remap() function:: + + public function _remap($method) + { + if ($method == 'some_method') + { + $this->$method(); + } + else + { + $this->default_method(); + } + } + +Any extra segments after the method name are passed into _remap() as an +optional second parameter. This array can be used in combination with +PHP's `call_user_func_array <http://php.net/call_user_func_array>`_ +to emulate CodeIgniter's default behavior. + +:: + + public function _remap($method, $params = array()) + { + $method = 'process_'.$method; + if (method_exists($this, $method)) + { + return call_user_func_array(array($this, $method), $params); + } + show_404(); + } + +Processing Output +================= + +CodeIgniter has an output class that takes care of sending your final +rendered data to the web browser automatically. More information on this +can be found in the :doc:`Views <views>` and :doc:`Output class <../libraries/output>` pages. In some cases, however, you +might want to post-process the finalized data in some way and send it to +the browser yourself. CodeIgniter permits you to add a function named +_output() to your controller that will receive the finalized output +data. + +.. important:: If your controller contains a function named _output(), + it will **always** be called by the output class instead of echoing the + finalized data directly. The first parameter of the function will + contain the finalized output. + +Here is an example:: + + public function _output($output) + { + echo $output; + } + +.. note:: Please note that your _output() function will receive the data in its + finalized state. Benchmark and memory usage data will be rendered, cache + files written (if you have caching enabled), and headers will be sent + (if you use that :doc:`feature <../libraries/output>`) before it is + handed off to the _output() function. + To have your controller's output cached properly, its _output() method + can use:: + + if ($this->output->cache_expiration > 0) + { + $this->output->_write_cache($output); + } + + If you are using this feature the page execution timer and memory usage + stats might not be perfectly accurate since they will not take into + acccount any further processing you do. For an alternate way to control + output *before* any of the final processing is done, please see the + available methods in the :doc:`Output Class <../libraries/output>`. + +Private Functions +================= + +In some cases you may want certain functions hidden from public access. +To make a function private, simply add an underscore as the name prefix +and it will not be served via a URL request. For example, if you were to +have a function like this:: + + private function _utility() + { + // some code + } + +Trying to access it via the URL, like this, will not work:: + + example.com/index.php/blog/_utility/ + +Organizing Your Controllers into Sub-folders +============================================ + +If you are building a large application you might find it convenient to +organize your controllers into sub-folders. CodeIgniter permits you to +do this. + +Simply create folders within your application/controllers directory and +place your controller classes within them. + +.. note:: When using this feature the first segment of your URI must + specify the folder. For example, lets say you have a controller located + here:: + + application/controllers/products/shoes.php + + To call the above controller your URI will look something like this:: + + example.com/index.php/products/shoes/show/123 + +Each of your sub-folders may contain a default controller which will be +called if the URL contains only the sub-folder. Simply name your default +controller as specified in your application/config/routes.php file + +CodeIgniter also permits you to remap your URIs using its :doc:`URI +Routing <routing>` feature. + +Class Constructors +================== + +If you intend to use a constructor in any of your Controllers, you +**MUST** place the following line of code in it:: + + parent::__construct(); + +The reason this line is necessary is because your local constructor will +be overriding the one in the parent controller class so we need to +manually call it. + +:: + + <?php + class Blog extends CI_Controller { + + public function __construct() + { + parent::__construct(); + // Your own constructor code + } + } + ?> + +Constructors are useful if you need to set some default values, or run a +default process when your class is instantiated. Constructors can't +return a value, but they can do some default work. + +Reserved Function Names +======================= + +Since your controller classes will extend the main application +controller you must be careful not to name your functions identically to +the ones used by that class, otherwise your local functions will +override them. See :doc:`Reserved Names <reserved_names>` for a full +list. + +That's it! +========== + +That, in a nutshell, is all there is to know about controllers. diff --git a/user_guide_src/source/general/core_classes.rst b/user_guide_src/source/general/core_classes.rst new file mode 100644 index 000000000..ac41407f7 --- /dev/null +++ b/user_guide_src/source/general/core_classes.rst @@ -0,0 +1,120 @@ +############################ +Creating Core System Classes +############################ + +Every time CodeIgniter runs there are several base classes that are +initialized automatically as part of the core framework. It is possible, +however, to swap any of the core system classes with your own versions +or even extend the core versions. + +**Most users will never have any need to do this, but the option to +replace or extend them does exist for those who would like to +significantly alter the CodeIgniter core.** + +.. note:: Messing with a core system class has a lot of implications, so + make sure you know what you are doing before attempting it. + +System Class List +================= + +The following is a list of the core system files that are invoked every +time CodeIgniter runs: + +- Benchmark +- Config +- Controller +- Exceptions +- Hooks +- Input +- Language +- Loader +- Log +- Output +- Router +- URI +- Utf8 + +Replacing Core Classes +====================== + +To use one of your own system classes instead of a default one simply +place your version inside your local application/core directory:: + + application/core/some-class.php + +If this directory does not exist you can create it. + +Any file named identically to one from the list above will be used +instead of the one normally used. + +Please note that your class must use CI as a prefix. For example, if +your file is named Input.php the class will be named:: + + class CI_Input { + + } + +Extending Core Class +==================== + +If all you need to do is add some functionality to an existing library - +perhaps add a function or two - then it's overkill to replace the entire +library with your version. In this case it's better to simply extend the +class. Extending a class is nearly identical to replacing a class with a +couple exceptions: + +- The class declaration must extend the parent class. +- Your new class name and filename must be prefixed with MY\_ (this + item is configurable. See below.). + +For example, to extend the native Input class you'll create a file named +application/core/MY_Input.php, and declare your class with:: + + class MY_Input extends CI_Input { + + } + +Note: If you need to use a constructor in your class make sure you +extend the parent constructor:: + + class MY_Input extends CI_Input { + + function __construct() + { + parent::__construct(); + } + } + +**Tip:** Any functions in your class that are named identically to the +functions in the parent class will be used instead of the native ones +(this is known as "method overriding"). This allows you to substantially +alter the CodeIgniter core. + +If you are extending the Controller core class, then be sure to extend +your new class in your application controller's constructors. + +:: + + class Welcome extends MY_Controller { + + function __construct() + { + parent::__construct(); + } + + function index() + { + $this->load->view('welcome_message'); + } + } + +Setting Your Own Prefix +----------------------- + +To set your own sub-class prefix, open your +application/config/config.php file and look for this item:: + + $config['subclass_prefix'] = 'MY_'; + +Please note that all native CodeIgniter libraries are prefixed with CI\_ +so DO NOT use that as your prefix. diff --git a/user_guide_src/source/general/creating_drivers.rst b/user_guide_src/source/general/creating_drivers.rst new file mode 100644 index 000000000..0e22e4f14 --- /dev/null +++ b/user_guide_src/source/general/creating_drivers.rst @@ -0,0 +1,20 @@ +################ +Creating Drivers +################ + +Driver Directory and File Structure +=================================== + +Sample driver directory and file structure layout: + +- /application/libraries/Driver_name + + - Driver_name.php + - drivers + + - Driver_name_subclass_1.php + - Driver_name_subclass_2.php + - Driver_name_subclass_3.php + +**NOTE:** In order to maintain compatibility on case-sensitive file +systems, the Driver_name directory must be ucfirst() diff --git a/user_guide_src/source/general/creating_libraries.rst b/user_guide_src/source/general/creating_libraries.rst new file mode 100644 index 000000000..bc545b483 --- /dev/null +++ b/user_guide_src/source/general/creating_libraries.rst @@ -0,0 +1,226 @@ +################## +Creating Libraries +################## + +When we use the term "Libraries" we are normally referring to the +classes that are located in the libraries directory and described in the +Class Reference of this user guide. In this case, however, we will +instead describe how you can create your own libraries within your +application/libraries directory in order to maintain separation between +your local resources and the global framework resources. + +As an added bonus, CodeIgniter permits your libraries to extend native +classes if you simply need to add some functionality to an existing +library. Or you can even replace native libraries just by placing +identically named versions in your application/libraries folder. + +In summary: + +- You can create entirely new libraries. +- You can extend native libraries. +- You can replace native libraries. + +The page below explains these three concepts in detail. + +.. note:: The Database classes can not be extended or replaced with your + own classes. All other classes are able to be replaced/extended. + +Storage +======= + +Your library classes should be placed within your application/libraries +folder, as this is where CodeIgniter will look for them when they are +initialized. + +Naming Conventions +================== + +- File names must be capitalized. For example: Myclass.php +- Class declarations must be capitalized. For example: class Myclass +- Class names and file names must match. + +The Class File +============== + +Classes should have this basic prototype (Note: We are using the name +Someclass purely as an example):: + + <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + + class Someclass { + + public function some_function() + { + } + } + + /* End of file Someclass.php */ + +Using Your Class +================ + +From within any of your :doc:`Controller <controllers>` functions you +can initialize your class using the standard:: + + $this->load->library('someclass'); + +Where *someclass* is the file name, without the ".php" file extension. +You can submit the file name capitalized or lower case. CodeIgniter +doesn't care. + +Once loaded you can access your class using the lower case version:: + + $this->someclass->some_function();Â // Object instances will always be lower case + +Passing Parameters When Initializing Your Class +=============================================== + +In the library loading function you can dynamically pass data as an +array via the second parameter and it will be passed to your class +constructor:: + + $params = array('type' => 'large', 'color' => 'red'); + + $this->load->library('Someclass', $params); + +If you use this feature you must set up your class constructor to expect +data:: + + <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + + class Someclass { + + public function __construct($params) + { + // Do something with $params + } + } + + ?> + +You can also pass parameters stored in a config file. Simply create a +config file named identically to the class file name and store it in +your application/config/ folder. Note that if you dynamically pass +parameters as described above, the config file option will not be +available. + +Utilizing CodeIgniter Resources within Your Library +=================================================== + +To access CodeIgniter's native resources within your library use the +get_instance() function. This function returns the CodeIgniter super +object. + +Normally from within your controller functions you will call any of the +available CodeIgniter functions using the $this construct:: + + $this->load->helper('url'); + $this->load->library('session'); + $this->config->item('base_url'); + // etc. + +$this, however, only works directly within your controllers, your +models, or your views. If you would like to use CodeIgniter's classes +from within your own custom classes you can do so as follows: + +First, assign the CodeIgniter object to a variable:: + + $CI =& get_instance(); + +Once you've assigned the object to a variable, you'll use that variable +*instead* of $this:: + + $CI =& get_instance(); + + $CI->load->helper('url'); + $CI->load->library('session'); + $CI->config->item('base_url'); + // etc. + +.. note:: You'll notice that the above get_instance() function is being + passed by reference:: + + $CI =& get_instance(); + + This is very important. Assigning by reference allows you to use the + original CodeIgniter object rather than creating a copy of it. + +Replacing Native Libraries with Your Versions +============================================= + +Simply by naming your class files identically to a native library will +cause CodeIgniter to use it instead of the native one. To use this +feature you must name the file and the class declaration exactly the +same as the native library. For example, to replace the native Email +library you'll create a file named application/libraries/Email.php, and +declare your class with:: + + class CI_Email { + + } + +Note that most native classes are prefixed with CI\_. + +To load your library you'll see the standard loading function:: + + $this->load->library('email'); + +.. note:: At this time the Database classes can not be replaced with + your own versions. + +Extending Native Libraries +========================== + +If all you need to do is add some functionality to an existing library - +perhaps add a function or two - then it's overkill to replace the entire +library with your version. In this case it's better to simply extend the +class. Extending a class is nearly identical to replacing a class with a +couple exceptions: + +- The class declaration must extend the parent class. +- Your new class name and filename must be prefixed with MY\_ (this + item is configurable. See below.). + +For example, to extend the native Email class you'll create a file named +application/libraries/MY_Email.php, and declare your class with:: + + class MY_Email extends CI_Email { + + } + +Note: If you need to use a constructor in your class make sure you +extend the parent constructor:: + + class MY_Email extends CI_Email { + + public function __construct() + { + parent::__construct(); + } + } + +Loading Your Sub-class +---------------------- + +To load your sub-class you'll use the standard syntax normally used. DO +NOT include your prefix. For example, to load the example above, which +extends the Email class, you will use:: + + $this->load->library('email'); + +Once loaded you will use the class variable as you normally would for +the class you are extending. In the case of the email class all calls +will use:: + + $this->email->some_function(); + +Setting Your Own Prefix +----------------------- + +To set your own sub-class prefix, open your +application/config/config.php file and look for this item:: + + $config['subclass_prefix'] = 'MY_'; + +Please note that all native CodeIgniter libraries are prefixed with CI\_ +so DO NOT use that as your prefix. diff --git a/user_guide_src/source/general/credits.rst b/user_guide_src/source/general/credits.rst new file mode 100644 index 000000000..2c7459894 --- /dev/null +++ b/user_guide_src/source/general/credits.rst @@ -0,0 +1,19 @@ +####### +Credits +####### + +CodeIgniter was originally developed by `Rick +Ellis <http://www.ellislab.com/>`_ (CEO of `EllisLab, +Inc. <http://ellislab.com/>`_). The framework was written for +performance in the real world, with many of the class libraries, +helpers, and sub-systems borrowed from the code-base of +`ExpressionEngine <http://www.expressionengine.com/>`_. + +It is currently developed and maintained by the ExpressionEngine +Development Team. +Bleeding edge development is spearheaded by the handpicked contributors +of the Reactor Team. + +A hat tip goes to Ruby on Rails for inspiring us to create a PHP +framework, and for bringing frameworks into the general consciousness of +the web community. diff --git a/user_guide_src/source/general/drivers.rst b/user_guide_src/source/general/drivers.rst new file mode 100644 index 000000000..e2ded62e2 --- /dev/null +++ b/user_guide_src/source/general/drivers.rst @@ -0,0 +1,40 @@ +######################### +Using CodeIgniter Drivers +######################### + +Drivers are a special type of Library that has a parent class and any +number of potential child classes. Child classes have access to the +parent class, but not their siblings. Drivers provide an elegant syntax +in your :doc:`controllers <controllers>` for libraries that benefit +from or require being broken down into discrete classes. + +Drivers are found in the system/libraries folder, in their own folder +which is identically named to the parent library class. Also inside that +folder is a subfolder named drivers, which contains all of the possible +child class files. + +To use a driver you will initialize it within a controller using the +following initialization function:: + + $this->load->driver('class name'); + +Where class name is the name of the driver class you want to invoke. For +example, to load a driver named "Some Parent" you would do this:: + + $this->load->driver('some_parent'); + +Methods of that class can then be invoked with:: + + $this->some_parent->some_method(); + +The child classes, the drivers themselves, can then be called directly +through the parent class, without initializing them:: + + $this->some_parent->child_one->some_method(); + $this->some_parent->child_two->another_method(); + +Creating Your Own Drivers +========================= + +Please read the section of the user guide that discusses how to :doc:`create +your own drivers <creating_drivers>`. diff --git a/user_guide_src/source/general/environments.rst b/user_guide_src/source/general/environments.rst new file mode 100644 index 000000000..40725feba --- /dev/null +++ b/user_guide_src/source/general/environments.rst @@ -0,0 +1,46 @@ +############################## +Handling Multiple Environments +############################## + +Developers often desire different system behavior depending on whether +an application is running in a development or production environment. +For example, verbose error output is something that would be useful +while developing an application, but it may also pose a security issue +when "live". + +The ENVIRONMENT Constant +======================== + +By default, CodeIgniter comes with the environment constant set to +'development'. At the top of index.php, you will see:: + + define('ENVIRONMENT', 'development'); + +In addition to affecting some basic framework behavior (see the next +section), you may use this constant in your own development to +differentiate between which environment you are running in. + +Effects On Default Framework Behavior +===================================== + +There are some places in the CodeIgniter system where the ENVIRONMENT +constant is used. This section describes how default framework behavior +is affected. + +Error Reporting +--------------- + +Setting the ENVIRONMENT constant to a value of 'development' will cause +all PHP errors to be rendered to the browser when they occur. +Conversely, setting the constant to 'production' will disable all error +output. Disabling error reporting in production is a :doc:`good security +practice <security>`. + +Configuration Files +------------------- + +Optionally, you can have CodeIgniter load environment-specific +configuration files. This may be useful for managing things like +differing API keys across multiple environments. This is described in +more detail in the environment section of the `Config +Class <../libraries/config.html#environments>`_ documentation. diff --git a/user_guide_src/source/general/errors.rst b/user_guide_src/source/general/errors.rst new file mode 100644 index 000000000..91b59140f --- /dev/null +++ b/user_guide_src/source/general/errors.rst @@ -0,0 +1,84 @@ +############## +Error Handling +############## + +CodeIgniter lets you build error reporting into your applications using +the functions described below. In addition, it has an error logging +class that permits error and debugging messages to be saved as text +files. + +.. note:: By default, CodeIgniter displays all PHP errors. You might + wish to change this behavior once your development is complete. You'll + find the error_reporting() function located at the top of your main + index.php file. Disabling error reporting will NOT prevent log files + from being written if there are errors. + +Unlike most systems in CodeIgniter, the error functions are simple +procedural interfaces that are available globally throughout the +application. This approach permits error messages to get triggered +without having to worry about class/function scoping. + +The following functions let you generate errors: + +show_error('message' [, int $status_code= 500 ] ) +=================================================== + +This function will display the error message supplied to it using the +following error template: + +application/errors/error_general.php + +The optional parameter $status_code determines what HTTP status code +should be sent with the error. + +show_404('page' [, 'log_error']) +================================== + +This function will display the 404 error message supplied to it using +the following error template: + +application/errors/error_404.php + +The function expects the string passed to it to be the file path to the +page that isn't found. Note that CodeIgniter automatically shows 404 +messages if controllers are not found. + +CodeIgniter automatically logs any show_404() calls. Setting the +optional second parameter to FALSE will skip logging. + +log_message('level', 'message') +================================ + +This function lets you write messages to your log files. You must supply +one of three "levels" in the first parameter, indicating what type of +message it is (debug, error, info), with the message itself in the +second parameter. Example:: + + if ($some_var == "") + { + log_message('error', 'Some variable did not contain a value.'); + } + else + { + log_message('debug', 'Some variable was correctly set'); + } + + log_message('info', 'The purpose of some variable is to provide some value.'); + +There are three message types: + +#. Error Messages. These are actual errors, such as PHP errors or user + errors. +#. Debug Messages. These are messages that assist in debugging. For + example, if a class has been initialized, you could log this as + debugging info. +#. Informational Messages. These are the lowest priority messages, + simply giving information regarding some process. CodeIgniter doesn't + natively generate any info messages but you may want to in your + application. + +.. note:: In order for the log file to actually be written, the "logs" + folder must be writable. In addition, you must set the "threshold" for + logging in application/config/config.php. You might, for example, only + want error messages to be logged, and not the other two types. If you + set it to zero logging will be disabled. diff --git a/user_guide_src/source/general/helpers.rst b/user_guide_src/source/general/helpers.rst new file mode 100644 index 000000000..3a98311a6 --- /dev/null +++ b/user_guide_src/source/general/helpers.rst @@ -0,0 +1,143 @@ +################ +Helper Functions +################ + +Helpers, as the name suggests, help you with tasks. Each helper file is +simply a collection of functions in a particular category. There are **URL +Helpers**, that assist in creating links, there are Form Helpers that help +you create form elements, **Text Helpers** perform various text formatting +routines, **Cookie Helpers** set and read cookies, File Helpers help you +deal with files, etc. + +Unlike most other systems in CodeIgniter, Helpers are not written in an +Object Oriented format. They are simple, procedural functions. Each +helper function performs one specific task, with no dependence on other +functions. + +CodeIgniter does not load Helper Files by default, so the first step in +using a Helper is to load it. Once loaded, it becomes globally available +in your :doc:`controller <../general/controllers>` and +:doc:`views <../general/views>`. + +Helpers are typically stored in your **system/helpers**, or +**application/helpers directory**. CodeIgniter will look first in your +**application/helpers directory**. If the directory does not exist or the +specified helper is not located there CI will instead look in your +global system/helpers folder. + +Loading a Helper +================ + +Loading a helper file is quite simple using the following function:: + + $this->load->helper('name'); + +Where **name** is the file name of the helper, without the .php file +extension or the "helper" part. + +For example, to load the **URL Helper** file, which is named +**url_helper.php**, you would do this:: + + $this->load->helper('url'); + +A helper can be loaded anywhere within your controller functions (or +even within your View files, although that's not a good practice), as +long as you load it before you use it. You can load your helpers in your +controller constructor so that they become available automatically in +any function, or you can load a helper in a specific function that needs +it. + +Note: The Helper loading function above does not return a value, so +don't try to assign it to a variable. Just use it as shown. + +Loading Multiple Helpers +======================== + +If you need to load more than one helper you can specify them in an +array, like this:: + + $this->load->helper( array('helper1', 'helper2', 'helper3') ); + +Auto-loading Helpers +==================== + +If you find that you need a particular helper globally throughout your +application, you can tell CodeIgniter to auto-load it during system +initialization. This is done by opening the **application/config/autoload.php** +file and adding the helper to the autoload array. + +Using a Helper +============== + +Once you've loaded the Helper File containing the function you intend to +use, you'll call it the way you would a standard PHP function. + +For example, to create a link using the anchor() function in one of your +view files you would do this:: + + <?php echo anchor('blog/comments', 'Click Here');?> + +Where "Click Here" is the name of the link, and "blog/comments" is the +URI to the controller/function you wish to link to. + +"Extending" Helpers +=================== + +To "extend" Helpers, create a file in your **application/helpers/** folder +with an identical name to the existing Helper, but prefixed with **MY\_** +(this item is configurable. See below.). + +If all you need to do is add some functionality to an existing helper - +perhaps add a function or two, or change how a particular helper +function operates - then it's overkill to replace the entire helper with +your version. In this case it's better to simply "extend" the Helper. +The term "extend" is used loosely since Helper functions are procedural +and discrete and cannot be extended in the traditional programmatic +sense. Under the hood, this gives you the ability to add to the +functions a Helper provides, or to modify how the native Helper +functions operate. + +For example, to extend the native **Array Helper** you'll create a file +named **application/helpers/MY_array_helper.php**, and add or override +functions:: + + // any_in_array() is not in the Array Helper, so it defines a new function + function any_in_array($needle, $haystack) + { + $needle = (is_array($needle)) ? $needle : array($needle); + + foreach ($needle as $item) + { + if (in_array($item, $haystack)) + { + return TRUE; + } + } + + return FALSE; + } + + // random_element() is included in Array Helper, so it overrides the native function + function random_element($array) + { + shuffle($array); + return array_pop($array); + } + +Setting Your Own Prefix +----------------------- + +The filename prefix for "extending" Helpers is the same used to extend +libraries and Core classes. To set your own prefix, open your +**application/config/config.php** file and look for this item:: + + $config['subclass_prefix'] = 'MY_'; + +Please note that all native CodeIgniter libraries are prefixed with **CI\_** +so DO NOT use that as your prefix. + +Now What? +========= + +In the Table of Contents you'll find a list of all the available Helper +Files. Browse each one to see what they do. diff --git a/user_guide_src/source/general/hooks.rst b/user_guide_src/source/general/hooks.rst new file mode 100644 index 000000000..65696f6c7 --- /dev/null +++ b/user_guide_src/source/general/hooks.rst @@ -0,0 +1,118 @@ +#################################### +Hooks - Extending the Framework Core +#################################### + +CodeIgniter's Hooks feature provides a means to tap into and modify the +inner workings of the framework without hacking the core files. When +CodeIgniter runs it follows a specific execution process, diagramed in +the :doc:`Application Flow <../overview/appflow>` page. There may be +instances, however, where you'd like to cause some action to take place +at a particular stage in the execution process. For example, you might +want to run a script right before your controllers get loaded, or right +after, or you might want to trigger one of your own scripts in some +other location. + +Enabling Hooks +============== + +The hooks feature can be globally enabled/disabled by setting the +following item in the application/config/config.php file:: + + $config['enable_hooks'] = TRUE; + +Defining a Hook +=============== + +Hooks are defined in application/config/hooks.php file. Each hook is +specified as an array with this prototype:: + + $hook['pre_controller'] = array( + 'class' => 'MyClass', + 'function' => 'Myfunction', + 'filename' => 'Myclass.php', + 'filepath' => 'hooks', + 'params' => array('beer', 'wine', 'snacks') + ); + +**Notes:** +The array index correlates to the name of the particular hook point you +want to use. In the above example the hook point is pre_controller. A +list of hook points is found below. The following items should be +defined in your associative hook array: + +- **class** The name of the class you wish to invoke. If you prefer to + use a procedural function instead of a class, leave this item blank. +- **function** The function name you wish to call. +- **filename** The file name containing your class/function. +- **filepath** The name of the directory containing your script. Note: + Your script must be located in a directory INSIDE your application + folder, so the file path is relative to that folder. For example, if + your script is located in application/hooks, you will simply use + hooks as your filepath. If your script is located in + application/hooks/utilities you will use hooks/utilities as your + filepath. No trailing slash. +- **params** Any parameters you wish to pass to your script. This item + is optional. + +Multiple Calls to the Same Hook +=============================== + +If want to use the same hook point with more then one script, simply +make your array declaration multi-dimensional, like this:: + + $hook['pre_controller'][] = array( + 'class' => 'MyClass', + 'function' => 'Myfunction', + 'filename' => 'Myclass.php', + 'filepath' => 'hooks', + 'params' => array('beer', 'wine', 'snacks') + ); + + $hook['pre_controller'][] = array( + 'class' => 'MyOtherClass', + 'function' => 'MyOtherfunction', + 'filename' => 'Myotherclass.php', + 'filepath' => 'hooks', + 'params' => array('red', 'yellow', 'blue') + ); + +Notice the brackets after each array index:: + + $hook['pre_controller'][] + +This permits you to have the same hook point with multiple scripts. The +order you define your array will be the execution order. + +Hook Points +=========== + +The following is a list of available hook points. + +- **pre_system** + Called very early during system execution. Only the benchmark and + hooks class have been loaded at this point. No routing or other + processes have happened. +- **pre_controller** + Called immediately prior to any of your controllers being called. + All base classes, routing, and security checks have been done. +- **post_controller_constructor** + Called immediately after your controller is instantiated, but prior + to any method calls happening. +- **post_controller** + Called immediately after your controller is fully executed. +- **display_override** + Overrides the _display() function, used to send the finalized page + to the web browser at the end of system execution. This permits you + to use your own display methodology. Note that you will need to + reference the CI superobject with $this->CI =& get_instance() and + then the finalized data will be available by calling + $this->CI->output->get_output() +- **cache_override** + Enables you to call your own function instead of the + _display_cache() function in the output class. This permits you to + use your own cache display mechanism. +- **post_system** + Called after the final rendered page is sent to the browser, at the + end of system execution after the finalized data is sent to the + browser. + diff --git a/user_guide_src/source/general/index.rst b/user_guide_src/source/general/index.rst new file mode 100644 index 000000000..2162b8140 --- /dev/null +++ b/user_guide_src/source/general/index.rst @@ -0,0 +1,32 @@ +############## +General Topics +############## + +.. toctree:: + :titlesonly: + + urls + controllers + reserved_names + views + models + Helpers <helpers> + libraries + creating_libraries + drivers + creating_drivers + core_classes + ancillary_classes + hooks + autoloader + common_functions + routing + errors + Caching <caching> + profiling + cli + managing_apps + environments + alternative_php + security + PHP Style Guide <styleguide> diff --git a/user_guide_src/source/general/libraries.rst b/user_guide_src/source/general/libraries.rst new file mode 100644 index 000000000..954a5b8f8 --- /dev/null +++ b/user_guide_src/source/general/libraries.rst @@ -0,0 +1,31 @@ +########################### +Using CodeIgniter Libraries +########################### + +All of the available libraries are located in your system/libraries +folder. In most cases, to use one of these classes involves initializing +it within a :doc:`controller <controllers>` using the following +initialization function:: + + $this->load->library('class name'); + +Where class name is the name of the class you want to invoke. For +example, to load the form validation class you would do this:: + + $this->load->library('form_validation'); + +Once initialized you can use it as indicated in the user guide page +corresponding to that class. + +Additionally, multiple libraries can be loaded at the same time by +passing an array of libraries to the load function. + +:: + + $this->load->library(array('email', 'table')); + +Creating Your Own Libraries +=========================== + +Please read the section of the user guide that discusses how to :doc:`create +your own libraries <creating_libraries>` diff --git a/user_guide_src/source/general/managing_apps.rst b/user_guide_src/source/general/managing_apps.rst new file mode 100644 index 000000000..996481354 --- /dev/null +++ b/user_guide_src/source/general/managing_apps.rst @@ -0,0 +1,65 @@ +########################## +Managing your Applications +########################## + +By default it is assumed that you only intend to use CodeIgniter to +manage one application, which you will build in your application/ +directory. It is possible, however, to have multiple sets of +applications that share a single CodeIgniter installation, or even to +rename or relocate your application folder. + +Renaming the Application Folder +=============================== + +If you would like to rename your application folder you may do so as +long as you open your main index.php file and set its name using the +$application_folder variable:: + + $application_folder = "application"; + +Relocating your Application Folder +================================== + +It is possible to move your application folder to a different location +on your server than your system folder. To do so open your main +index.php and set a *full server path* in the $application_folder +variable. + +:: + + $application_folder = "/Path/to/your/application"; + +Running Multiple Applications with one CodeIgniter Installation +=============================================================== + +If you would like to share a common CodeIgniter installation to manage +several different applications simply put all of the directories located +inside your application folder into their own sub-folder. + +For example, let's say you want to create two applications, "foo" and +"bar". You could structure your application folders like this:: + + applications/foo/ + applications/foo/config/ + applications/foo/controllers/ + applications/foo/errors/ + applications/foo/libraries/ + applications/foo/models/ + applications/foo/views/ + applications/bar/ + applications/bar/config/ + applications/bar/controllers/ + applications/bar/errors/ + applications/bar/libraries/ + applications/bar/models/ + applications/bar/views/ + +To select a particular application for use requires that you open your +main index.php file and set the $application_folder variable. For +example, to select the "foo" application for use you would do this:: + + $application_folder = "applications/foo"; + +.. note:: Each of your applications will need its own index.php file + which calls the desired application. The index.php file can be named + anything you want. diff --git a/user_guide_src/source/general/models.rst b/user_guide_src/source/general/models.rst new file mode 100644 index 000000000..b816f958a --- /dev/null +++ b/user_guide_src/source/general/models.rst @@ -0,0 +1,184 @@ +###### +Models +###### + +Models are **optionally** available for those who want to use a more +traditional MVC approach. + +.. contents:: Page Contents + +What is a Model? +================ + +Models are PHP classes that are designed to work with information in +your database. For example, let's say you use CodeIgniter to manage a +blog. You might have a model class that contains functions to insert, +update, and retrieve your blog data. Here is an example of what such a +model class might look like:: + + class Blogmodel extends CI_Model { + + var $title = ''; + var $content = ''; + var $date = ''; + + function __construct() + { + // Call the Model constructor + parent::__construct(); + } + + function get_last_ten_entries() + { + $query = $this->db->get('entries', 10); + return $query->result(); + } + + function insert_entry() + { + $this->title = $_POST['title']; // please read the below note + $this->content = $_POST['content']; + $this->date = time(); + + $this->db->insert('entries', $this); + } + + function update_entry() + { + $this->title = $_POST['title']; + $this->content = $_POST['content']; + $this->date = time(); + + $this->db->update('entries', $this, array('id' => $_POST['id'])); + } + + } + +.. note:: The functions in the above example use the :doc:`Active + Record <../database/active_record>` database functions. + +.. note:: For the sake of simplicity in this example we're using $_POST + directly. This is generally bad practice, and a more common approach + would be to use the :doc:`Input Class <../libraries/input>` + $this->input->post('title') + +Anatomy of a Model +================== + +Model classes are stored in your **application/models/ folder**. They can be +nested within sub-folders if you want this type of organization. + +The basic prototype for a model class is this:: + + class Model_name extends CI_Model { + + function __construct() + { + parent::__construct(); + } + } + +Where **Model_name** is the name of your class. Class names **must** have +the first letter capitalized with the rest of the name lowercase. Make +sure your class extends the base Model class. + +The file name will be a lower case version of your class name. For +example, if your class is this:: + + class User_model extends CI_Model { + + function __construct() + { + parent::__construct(); + } + } + +Your file will be this:: + + application/models/user_model.php + +Loading a Model +=============== + +Your models will typically be loaded and called from within your +:doc:`controller <controllers>` functions. To load a model you will use +the following function:: + + $this->load->model('Model_name'); + +If your model is located in a sub-folder, include the relative path from +your models folder. For example, if you have a model located at +application/models/blog/queries.php you'll load it using:: + + $this->load->model('blog/queries'); + +Once loaded, you will access your model functions using an object with +the same name as your class:: + + $this->load->model('Model_name'); + + $this->Model_name->function(); + +If you would like your model assigned to a different object name you can +specify it via the second parameter of the loading function:: + + $this->load->model('Model_name', 'fubar'); + + $this->fubar->function(); + +Here is an example of a controller, that loads a model, then serves a +view:: + + class Blog_controller extends CI_Controller { + + function blog() + { + $this->load->model('Blog'); + + $data['query'] = $this->Blog->get_last_ten_entries(); + + $this->load->view('blog', $data); + } + } + + +Auto-loading Models +=================== + +If you find that you need a particular model globally throughout your +application, you can tell CodeIgniter to auto-load it during system +initialization. This is done by opening the +**application/config/autoload.php** file and adding the model to the +autoload array. + +Connecting to your Database +=========================== + +When a model is loaded it does **NOT** connect automatically to your +database. The following options for connecting are available to you: + +- You can connect using the standard database methods :doc:`described + here <../database/connecting>`, either from within your + Controller class or your Model class. +- You can tell the model loading function to auto-connect by passing + TRUE (boolean) via the third parameter, and connectivity settings, as + defined in your database config file will be used: + :: + + $this->load->model('Model_name', '', TRUE); + +- You can manually pass database connectivity settings via the third + parameter:: + + $config['hostname'] = "localhost"; + $config['username'] = "myusername"; + $config['password'] = "mypassword"; + $config['database'] = "mydatabase"; + $config['dbdriver'] = "mysql"; + $config['dbprefix'] = ""; + $config['pconnect'] = FALSE; + $config['db_debug'] = TRUE; + + $this->load->model('Model_name', '', $config); + + diff --git a/user_guide_src/source/general/profiling.rst b/user_guide_src/source/general/profiling.rst new file mode 100644 index 000000000..437635289 --- /dev/null +++ b/user_guide_src/source/general/profiling.rst @@ -0,0 +1,83 @@ +########################## +Profiling Your Application +########################## + +The Profiler Class will display benchmark results, queries you have run, +and $_POST data at the bottom of your pages. This information can be +useful during development in order to help with debugging and +optimization. + +Initializing the Class +====================== + +.. important:: This class does NOT need to be initialized. It is loaded + automatically by the :doc:`Output Class <../libraries/output>` if + profiling is enabled as shown below. + +Enabling the Profiler +===================== + +To enable the profiler place the following function anywhere within your +:doc:`Controller <controllers>` functions:: + + $this->output->enable_profiler(TRUE); + +When enabled a report will be generated and inserted at the bottom of +your pages. + +To disable the profiler you will use:: + + $this->output->enable_profiler(FALSE); + +Setting Benchmark Points +======================== + +In order for the Profiler to compile and display your benchmark data you +must name your mark points using specific syntax. + +Please read the information on setting Benchmark points in :doc:`Benchmark +Class <../libraries/benchmark>` page. + +Enabling and Disabling Profiler Sections +======================================== + +Each section of Profiler data can be enabled or disabled by setting a +corresponding config variable to TRUE or FALSE. This can be done one of +two ways. First, you can set application wide defaults with the +application/config/profiler.php config file. + +:: + + $config['config'] = FALSE; + $config['queries'] = FALSE; + +In your controllers, you can override the defaults and config file +values by calling the set_profiler_sections() method of the :doc:`Output +class <../libraries/output>`:: + + $sections = array( + 'config' => TRUE, + 'queries' => TRUE + ); + + $this->output->set_profiler_sections($sections); + +Available sections and the array key used to access them are described +in the table below. + +======================= =================================================================== ======== +Key Description Default +======================= =================================================================== ======== +**benchmarks** Elapsed time of Benchmark points and total execution time TRUE +**config** CodeIgniter Config variables TRUE +**controller_info** The Controller class and method requested TRUE +**get** Any GET data passed in the request TRUE +**http_headers** The HTTP headers for the current request TRUE +**memory_usage** Amount of memory consumed by the current request, in bytes TRUE +**post** Any POST data passed in the request TRUE +**queries** Listing of all database queries executed, including execution time TRUE +**uri_string** The URI of the current request TRUE +**session_data** Data stored in the current session TRUE +**query_toggle_count** The number of queries after which the query block will default to 25 + hidden. +======================= =================================================================== ========
\ No newline at end of file diff --git a/user_guide_src/source/general/quick_reference.rst b/user_guide_src/source/general/quick_reference.rst new file mode 100644 index 000000000..b9108a528 --- /dev/null +++ b/user_guide_src/source/general/quick_reference.rst @@ -0,0 +1,11 @@ +##################### +Quick Reference Chart +##################### + +For a PDF version of this chart, `click +here <http://codeigniter.com/download_files/ci_quick_ref.pdf>`_. + +.. figure:: ../images/ci_quick_ref.png + :align: center + :alt: + diff --git a/user_guide_src/source/general/requirements.rst b/user_guide_src/source/general/requirements.rst new file mode 100644 index 000000000..38623557d --- /dev/null +++ b/user_guide_src/source/general/requirements.rst @@ -0,0 +1,8 @@ +################### +Server Requirements +################### + +- `PHP <http://www.php.net/>`_ version 5.1.6 or newer. +- A Database is required for most web application programming. Current + supported databases are MySQL (4.1+), MySQLi, MS SQL, Postgres, Oracle, + SQLite, ODBC and CUBRID.
\ No newline at end of file diff --git a/user_guide_src/source/general/reserved_names.rst b/user_guide_src/source/general/reserved_names.rst new file mode 100644 index 000000000..5ce7fc2ff --- /dev/null +++ b/user_guide_src/source/general/reserved_names.rst @@ -0,0 +1,66 @@ +############## +Reserved Names +############## + +In order to help out, CodeIgniter uses a series of functions and names +in its operation. Because of this, some names cannot be used by a +developer. Following is a list of reserved names that cannot be used. + +Controller names +---------------- + +Since your controller classes will extend the main application +controller you must be careful not to name your functions identically to +the ones used by that class, otherwise your local functions will +override them. The following is a list of reserved names. Do not name +your controller any of these: + +- Controller +- CI_Base +- _ci_initialize +- Default +- index + +Functions +--------- + +- is_really_writable() +- load_class() +- get_config() +- config_item() +- show_error() +- show_404() +- log_message() +- _exception_handler() +- get_instance() + +Variables +--------- + +- $config +- $mimes +- $lang + +Constants +--------- + +- ENVIRONMENT +- EXT +- FCPATH +- SELF +- BASEPATH +- APPPATH +- CI_VERSION +- FILE_READ_MODE +- FILE_WRITE_MODE +- DIR_READ_MODE +- DIR_WRITE_MODE +- FOPEN_READ +- FOPEN_READ_WRITE +- FOPEN_WRITE_CREATE_DESTRUCTIVE +- FOPEN_READ_WRITE_CREATE_DESTRUCTIVE +- FOPEN_WRITE_CREATE +- FOPEN_READ_WRITE_CREATE +- FOPEN_WRITE_CREATE_STRICT +- FOPEN_READ_WRITE_CREATE_STRICT + diff --git a/user_guide_src/source/general/routing.rst b/user_guide_src/source/general/routing.rst new file mode 100644 index 000000000..45950fc11 --- /dev/null +++ b/user_guide_src/source/general/routing.rst @@ -0,0 +1,133 @@ +########### +URI Routing +########### + +Typically there is a one-to-one relationship between a URL string and +its corresponding controller class/method. The segments in a URI +normally follow this pattern:: + + example.com/class/function/id/ + +In some instances, however, you may want to remap this relationship so +that a different class/function can be called instead of the one +corresponding to the URL. + +For example, lets say you want your URLs to have this prototype: + +example.com/product/1/ +example.com/product/2/ +example.com/product/3/ +example.com/product/4/ + +Normally the second segment of the URL is reserved for the function +name, but in the example above it instead has a product ID. To overcome +this, CodeIgniter allows you to remap the URI handler. + +Setting your own routing rules +============================== + +Routing rules are defined in your application/config/routes.php file. In +it you'll see an array called $route that permits you to specify your +own routing criteria. Routes can either be specified using wildcards or +Regular Expressions + +Wildcards +========= + +A typical wildcard route might look something like this:: + + $route['product/:num'] = "catalog/product_lookup"; + +In a route, the array key contains the URI to be matched, while the +array value contains the destination it should be re-routed to. In the +above example, if the literal word "product" is found in the first +segment of the URL, and a number is found in the second segment, the +"catalog" class and the "product_lookup" method are instead used. + +You can match literal values or you can use two wildcard types: + +**(:num)** will match a segment containing only numbers. + **(:any)** will match a segment containing any character. + +.. note:: Routes will run in the order they are defined. Higher routes + will always take precedence over lower ones. + +Examples +======== + +Here are a few routing examples:: + + $route['journals'] = "blogs"; + +A URL containing the word "journals" in the first segment will be +remapped to the "blogs" class. + +:: + + $route['blog/joe'] = "blogs/users/34"; + +A URL containing the segments blog/joe will be remapped to the "blogs" +class and the "users" method. The ID will be set to "34". + +:: + + $route['product/(:any)'] = "catalog/product_lookup"; + +A URL with "product" as the first segment, and anything in the second +will be remapped to the "catalog" class and the "product_lookup" +method. + +:: + + $route['product/(:num)'] = "catalog/product_lookup_by_id/$1"; + +A URL with "product" as the first segment, and a number in the second +will be remapped to the "catalog" class and the +"product_lookup_by_id" method passing in the match as a variable to +the function. + +.. important:: Do not use leading/trailing slashes. + +Regular Expressions +=================== + +If you prefer you can use regular expressions to define your routing +rules. Any valid regular expression is allowed, as are back-references. + +.. note:: If you use back-references you must use the dollar syntax + rather than the double backslash syntax. + +A typical RegEx route might look something like this:: + + $route['products/([a-z]+)/(\d+)'] = "$1/id_$2"; + +In the above example, a URI similar to products/shirts/123 would instead +call the shirts controller class and the id_123 function. + +You can also mix and match wildcards with regular expressions. + +Reserved Routes +=============== + +There are two reserved routes:: + + $route['default_controller'] = 'welcome'; + +This route indicates which controller class should be loaded if the URI +contains no data, which will be the case when people load your root URL. +In the above example, the "welcome" class would be loaded. You are +encouraged to always have a default route otherwise a 404 page will +appear by default. + +:: + + $route['404_override'] = ''; + +This route indicates which controller class should be loaded if the +requested controller is not found. It will override the default 404 +error page. It won't affect to the show_404() function, which will +continue loading the default error_404.php file at +application/errors/error_404.php. + +.. important:: The reserved routes must come before any wildcard or + regular expression routes. diff --git a/user_guide_src/source/general/security.rst b/user_guide_src/source/general/security.rst new file mode 100644 index 000000000..4d7a213d1 --- /dev/null +++ b/user_guide_src/source/general/security.rst @@ -0,0 +1,90 @@ +######## +Security +######## + +This page describes some "best practices" regarding web security, and +details CodeIgniter's internal security features. + +URI Security +============ + +CodeIgniter is fairly restrictive regarding which characters it allows +in your URI strings in order to help minimize the possibility that +malicious data can be passed to your application. URIs may only contain +the following: + +- Alpha-numeric text +- Tilde: ~ +- Period: . +- Colon: : +- Underscore: \_ +- Dash: - + +Register_globals +================= + +During system initialization all global variables are unset, except +those found in the $_GET, $_POST, and $_COOKIE arrays. The unsetting +routine is effectively the same as register_globals = off. + +error_reporting +================ + +In production environments, it is typically desirable to disable PHP's +error reporting by setting the internal error_reporting flag to a value +of 0. This disables native PHP errors from being rendered as output, +which may potentially contain sensitive information. + +Setting CodeIgniter's **ENVIRONMENT** constant in index.php to a value of +**\'production\'** will turn off these errors. In development mode, it is +recommended that a value of 'development' is used. More information +about differentiating between environments can be found on the :doc:`Handling +Environments <environments>` page. + +magic_quotes_runtime +====================== + +The magic_quotes_runtime directive is turned off during system +initialization so that you don't have to remove slashes when retrieving +data from your database. + +************** +Best Practices +************** + +Before accepting any data into your application, whether it be POST data +from a form submission, COOKIE data, URI data, XML-RPC data, or even +data from the SERVER array, you are encouraged to practice this three +step approach: + +#. Filter the data as if it were tainted. +#. Validate the data to ensure it conforms to the correct type, length, + size, etc. (sometimes this step can replace step one) +#. Escape the data before submitting it into your database. + +CodeIgniter provides the following functions to assist in this process: + +XSS Filtering +============= + +CodeIgniter comes with a Cross Site Scripting filter. This filter +looks for commonly used techniques to embed malicious Javascript into +your data, or other types of code that attempt to hijack cookies or +do other malicious things. The XSS Filter is described +:doc:`here <../libraries/security>`. + +Validate the data +================= + +CodeIgniter has a :doc:`Form Validation +Class <../libraries/form_validation>` that assists you in +validating, filtering, and prepping your data. + +Escape all data before database insertion +========================================= + +Never insert information into your database without escaping it. +Please see the section that discusses +:doc:`queries <../database/queries>` for more information. + + diff --git a/user_guide_src/source/general/styleguide.rst b/user_guide_src/source/general/styleguide.rst new file mode 100644 index 000000000..b3dc08871 --- /dev/null +++ b/user_guide_src/source/general/styleguide.rst @@ -0,0 +1,652 @@ +############### +PHP Style Guide +############### + + +The following page describes the use of coding rules adhered to when +developing CodeIgniter. + +.. contents:: Table of Contents + +File Format +=========== + +Files should be saved with Unicode (UTF-8) encoding. The BOM should +*not* be used. Unlike UTF-16 and UTF-32, there's no byte order to +indicate in a UTF-8 encoded file, and the BOM can have a negative side +effect in PHP of sending output, preventing the application from being +able to set its own headers. Unix line endings should be used (LF). + +Here is how to apply these settings in some of the more common text +editors. Instructions for your text editor may vary; check your text +editor's documentation. + +TextMate +'''''''' + +#. Open the Application Preferences +#. Click Advanced, and then the "Saving" tab +#. In "File Encoding", select "UTF-8 (recommended)" +#. In "Line Endings", select "LF (recommended)" +#. *Optional:* Check "Use for existing files as well" if you wish to + modify the line endings of files you open to your new preference. + +BBEdit +'''''' + +#. Open the Application Preferences +#. Select "Text Encodings" on the left. +#. In "Default text encoding for new documents", select "Unicode (UTF-8, + no BOM)" +#. *Optional:* In "If file's encoding can't be guessed, use", select + "Unicode (UTF-8, no BOM)" +#. Select "Text Files" on the left. +#. In "Default line breaks", select "Mac OS X and Unix (LF)" + +PHP Closing Tag +=============== + +The PHP closing tag on a PHP document **?>** is optional to the PHP +parser. However, if used, any whitespace following the closing tag, +whether introduced by the developer, user, or an FTP application, can +cause unwanted output, PHP errors, or if the latter are suppressed, +blank pages. For this reason, all PHP files should **OMIT** the closing +PHP tag, and instead use a comment block to mark the end of file and +it's location relative to the application root. This allows you to still +identify a file as being complete and not truncated. + +**INCORRECT**:: + + <?php + + echo "Here's my code!"; + + ?> + +**CORRECT**:: + + <?php + + echo "Here's my code!"; + + /* End of file myfile.php */ + /* Location: ./system/modules/mymodule/myfile.php */ + +Class and Method Naming +======================= + +Class names should always start with an uppercase letter. Multiple words +should be separated with an underscore, and not CamelCased. All other +class methods should be entirely lowercased and named to clearly +indicate their function, preferably including a verb. Try to avoid +overly long and verbose names. + +**INCORRECT**:: + + class superclass + class SuperClass + +**CORRECT**:: + + class Super_class + +:: + + class Super_class { + + function __construct() + { + + } + } + +Examples of improper and proper method naming: + +**INCORRECT**:: + + function fileproperties() // not descriptive and needs underscore separator + function fileProperties() // not descriptive and uses CamelCase + function getfileproperties() // Better! But still missing underscore separator + function getFileProperties() // uses CamelCase + function get_the_file_properties_from_the_file() // wordy + +**CORRECT**:: + + function get_file_properties() // descriptive, underscore separator, and all lowercase letters + +Variable Names +============== + +The guidelines for variable naming is very similar to that used for +class methods. Namely, variables should contain only lowercase letters, +use underscore separators, and be reasonably named to indicate their +purpose and contents. Very short, non-word variables should only be used +as iterators in for() loops. + +**INCORRECT**:: + + $j = 'foo'; // single letter variables should only be used in for() loops + $Str // contains uppercase letters + $bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning + $groupid // multiple words, needs underscore separator + $name_of_last_city_used // too long + +**CORRECT**:: + + for ($j = 0; $j < 10; $j++) + $str + $buffer + $group_id + $last_city + +Commenting +========== + +In general, code should be commented prolifically. It not only helps +describe the flow and intent of the code for less experienced +programmers, but can prove invaluable when returning to your own code +months down the line. There is not a required format for comments, but +the following are recommended. + +`DocBlock <http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html#basics.docblock>`_ +style comments preceding class and method declarations so they can be +picked up by IDEs:: + + /** + * Super Class + * + * @package Package Name + * @subpackage Subpackage + * @category Category + * @author Author Name + * @link http://example.com + */ + class Super_class { + +:: + + /** + * Encodes string for use in XML + * + * @access public + * @param string + * @return string + */ + function xml_encode($str) + +Use single line comments within code, leaving a blank line between large +comment blocks and code. + +:: + + // break up the string by newlines + $parts = explode("\n", $str); + + // A longer comment that needs to give greater detail on what is + // occurring and why can use multiple single-line comments. Try to + // keep the width reasonable, around 70 characters is the easiest to + // read. Don't hesitate to link to permanent external resources + // that may provide greater detail: + // + // http://example.com/information_about_something/in_particular/ + + $parts = $this->foo($parts); + +Constants +========= + +Constants follow the same guidelines as do variables, except constants +should always be fully uppercase. *Always use CodeIgniter constants when +appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc.* + +**INCORRECT**:: + + myConstant // missing underscore separator and not fully uppercase + N // no single-letter constants + S_C_VER // not descriptive + $str = str_replace('{foo}', 'bar', $str); // should use LD and RD constants + +**CORRECT**:: + + MY_CONSTANT + NEWLINE + SUPER_CLASS_VERSION + $str = str_replace(LD.'foo'.RD, 'bar', $str); + +TRUE, FALSE, and NULL +===================== + +**TRUE**, **FALSE**, and **NULL** keywords should always be fully +uppercase. + +**INCORRECT**:: + + if ($foo == true) + $bar = false; + function foo($bar = null) + +**CORRECT**:: + + if ($foo == TRUE) + $bar = FALSE; + function foo($bar = NULL) + +Logical Operators +================= + +Use of **\|\|** is discouraged as its clarity on some output devices is +low (looking like the number 11 for instance). **&&** is preferred over +**AND** but either are acceptable, and a space should always precede and +follow **!**. + +**INCORRECT**:: + + if ($foo || $bar) + if ($foo AND $bar) // okay but not recommended for common syntax highlighting applications + if (!$foo) + if (! is_array($foo)) + +**CORRECT**:: + + if ($foo OR $bar) + if ($foo && $bar) // recommended + if ( ! $foo) + if ( ! is_array($foo)) + + +Comparing Return Values and Typecasting +======================================= + +Some PHP functions return FALSE on failure, but may also have a valid +return value of "" or 0, which would evaluate to FALSE in loose +comparisons. Be explicit by comparing the variable type when using these +return values in conditionals to ensure the return value is indeed what +you expect, and not a value that has an equivalent loose-type +evaluation. + +Use the same stringency in returning and checking your own variables. +Use **===** and **!==** as necessary. + +**INCORRECT**:: + + // If 'foo' is at the beginning of the string, strpos will return a 0, + // resulting in this conditional evaluating as TRUE + if (strpos($str, 'foo') == FALSE) + +**CORRECT**:: + + if (strpos($str, 'foo') === FALSE) + +**INCORRECT**:: + + function build_string($str = "") + { + if ($str == "") // uh-oh! What if FALSE or the integer 0 is passed as an argument? + { + + } + } + +**CORRECT**:: + + function build_string($str = "") + { + if ($str === "") + { + + } + } + + +See also information regarding +`typecasting <http://us3.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting>`_, +which can be quite useful. Typecasting has a slightly different effect +which may be desirable. When casting a variable as a string, for +instance, NULL and boolean FALSE variables become empty strings, 0 (and +other numbers) become strings of digits, and boolean TRUE becomes "1":: + + $str = (string) $str; // cast $str as a string + +Debugging Code +============== + +No debugging code can be left in place for submitted add-ons unless it +is commented out, i.e. no var_dump(), print_r(), die(), and exit() +calls that were used while creating the add-on, unless they are +commented out. + +:: + + // print_r($foo); + +Whitespace in Files +=================== + +No whitespace can precede the opening PHP tag or follow the closing PHP +tag. Output is buffered, so whitespace in your files can cause output to +begin before CodeIgniter outputs its content, leading to errors and an +inability for CodeIgniter to send proper headers. In the examples below, +select the text with your mouse to reveal the incorrect whitespace. + + +Compatibility +============= + +Unless specifically mentioned in your add-on's documentation, all code +must be compatible with PHP version 5.1+. Additionally, do not use PHP +functions that require non-default libraries to be installed unless your +code contains an alternative method when the function is not available, +or you implicitly document that your add-on requires said PHP libraries. + +Class and File Names using Common Words +======================================= + +When your class or filename is a common word, or might quite likely be +identically named in another PHP script, provide a unique prefix to help +prevent collision. Always realize that your end users may be running +other add-ons or third party PHP scripts. Choose a prefix that is unique +to your identity as a developer or company. + +**INCORRECT**:: + + class Email pi.email.php + class Xml ext.xml.php + class Import mod.import.php + +**CORRECT**:: + + class Pre_email pi.pre_email.php + class Pre_xml ext.pre_xml.php + class Pre_import mod.pre_import.php + +Database Table Names +==================== + +Any tables that your add-on might use must use the 'exp\_' prefix, +followed by a prefix uniquely identifying you as the developer or +company, and then a short descriptive table name. You do not need to be +concerned about the database prefix being used on the user's +installation, as CodeIgniter's database class will automatically convert +'exp\_' to what is actually being used. + +**INCORRECT**:: + + email_addresses // missing both prefixes + pre_email_addresses // missing exp_ prefix + exp_email_addresses // missing unique prefix + +**CORRECT**:: + + exp_pre_email_addresses + +.. note:: Be mindful that MySQL has a limit of 64 characters for table + names. This should not be an issue as table names that would exceed this + would likely have unreasonable names. For instance, the following table + name exceeds this limitation by one character. Silly, no? + **exp_pre_email_addresses_of_registered_users_in_seattle_washington** + +One File per Class +================== + +Use separate files for each class your add-on uses, unless the classes +are *closely related*. An example of CodeIgniter files that contains +multiple classes is the Database class file, which contains both the DB +class and the DB_Cache class, and the Magpie plugin, which contains +both the Magpie and Snoopy classes. + +Whitespace +========== + +Use tabs for whitespace in your code, not spaces. This may seem like a +small thing, but using tabs instead of whitespace allows the developer +looking at your code to have indentation at levels that they prefer and +customize in whatever application they use. And as a side benefit, it +results in (slightly) more compact files, storing one tab character +versus, say, four space characters. + +Line Breaks +=========== + +Files must be saved with Unix line breaks. This is more of an issue for +developers who work in Windows, but in any case ensure that your text +editor is setup to save files with Unix line breaks. + +Code Indenting +============== + +Use Allman style indenting. With the exception of Class declarations, +braces are always placed on a line by themselves, and indented at the +same level as the control statement that "owns" them. + +**INCORRECT**:: + + function foo($bar) { + // ... + } + + foreach ($arr as $key => $val) { + // ... + } + + if ($foo == $bar) { + // ... + } else { + // ... + } + + for ($i = 0; $i < 10; $i++) + { + for ($j = 0; $j < 10; $j++) + { + // ... + } + } + +**CORRECT**:: + + function foo($bar) + { + // ... + } + + foreach ($arr as $key => $val) + { + // ... + } + + if ($foo == $bar) + { + // ... + } + else + { + // ... + } + + for ($i = 0; $i < 10; $i++) + { + for ($j = 0; $j < 10; $j++) + { + // ... + } + } + +Bracket and Parenthetic Spacing +=============================== + +In general, parenthesis and brackets should not use any additional +spaces. The exception is that a space should always follow PHP control +structures that accept arguments with parenthesis (declare, do-while, +elseif, for, foreach, if, switch, while), to help distinguish them from +functions and increase readability. + +**INCORRECT**:: + + $arr[ $foo ] = 'foo'; + +**CORRECT**:: + + $arr[$foo] = 'foo'; // no spaces around array keys + +**INCORRECT**:: + + function foo ( $bar ) + { + + } + +**CORRECT**:: + + function foo($bar) // no spaces around parenthesis in function declarations + { + + } + +**INCORRECT**:: + + foreach( $query->result() as $row ) + +**CORRECT**:: + + foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis + +Localized Text +============== + +Any text that is output in the control panel should use language +variables in your lang file to allow localization. + +**INCORRECT**:: + + return "Invalid Selection"; + +**CORRECT**:: + + return $this->lang->line('invalid_selection'); + +Private Methods and Variables +============================= + +Methods and variables that are only accessed internally by your class, +such as utility and helper functions that your public methods use for +code abstraction, should be prefixed with an underscore. + +:: + + convert_text() // public method + _convert_text() // private method + +PHP Errors +========== + +Code must run error free and not rely on warnings and notices to be +hidden to meet this requirement. For instance, never access a variable +that you did not set yourself (such as $_POST array keys) without first +checking to see that it isset(). + +Make sure that while developing your add-on, error reporting is enabled +for ALL users, and that display_errors is enabled in the PHP +environment. You can check this setting with:: + + if (ini_get('display_errors') == 1) + { + exit "Enabled"; + } + +On some servers where display_errors is disabled, and you do not have +the ability to change this in the php.ini, you can often enable it with:: + + ini_set('display_errors', 1); + +**NOTE:** Setting the +`display_errors <http://us.php.net/manual/en/ref.errorfunc.php#ini.display-errors>`_ +setting with ini_set() at runtime is not identical to having it enabled +in the PHP environment. Namely, it will not have any effect if the +script has fatal errors + +Short Open Tags +=============== + +Always use full PHP opening tags, in case a server does not have +short_open_tag enabled. + +**INCORRECT**:: + + <? echo $foo; ?> + + <?=$foo?> + +**CORRECT**:: + + <?php echo $foo; ?> + +One Statement Per Line +====================== + +Never combine statements on one line. + +**INCORRECT**:: + + $foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag); + +**CORRECT**:: + + $foo = 'this'; + $bar = 'that'; + $bat = str_replace($foo, $bar, $bag); + +Strings +======= + +Always use single quoted strings unless you need variables parsed, and +in cases where you do need variables parsed, use braces to prevent +greedy token parsing. You may also use double-quoted strings if the +string contains single quotes, so you do not have to use escape +characters. + +**INCORRECT**:: + + "My String" // no variable parsing, so no use for double quotes + "My string $foo" // needs braces + 'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly + +**CORRECT**:: + + 'My String' + "My string {$foo}" + "SELECT foo FROM bar WHERE baz = 'bag'" + +SQL Queries +=========== + +MySQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, +AS, JOIN, ON, IN, etc. + +Break up long queries into multiple lines for legibility, preferably +breaking for each clause. + +**INCORRECT**:: + + // keywords are lowercase and query is too long for + // a single line (... indicates continuation of line) + $query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses + ...where foo != 'oof' and baz != 'zab' order by foobaz limit 5, 100"); + +**CORRECT**:: + + $query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz + FROM exp_pre_email_addresses + WHERE foo != 'oof' + AND baz != 'zab' + ORDER BY foobaz + LIMIT 5, 100"); + +Default Function Arguments +========================== + +Whenever appropriate, provide function argument defaults, which helps +prevent PHP errors with mistaken calls and provides common fallback +values which can save a few lines of code. Example:: + + function foo($bar = '', $baz = FALSE) + diff --git a/user_guide_src/source/general/urls.rst b/user_guide_src/source/general/urls.rst new file mode 100644 index 000000000..211537675 --- /dev/null +++ b/user_guide_src/source/general/urls.rst @@ -0,0 +1,93 @@ +################ +CodeIgniter URLs +################ + +By default, URLs in CodeIgniter are designed to be search-engine and +human friendly. Rather than using the standard "query string" approach +to URLs that is synonymous with dynamic systems, CodeIgniter uses a +**segment-based** approach:: + + example.com/news/article/my_article + +.. note:: Query string URLs can be optionally enabled, as described + below. + +URI Segments +============ + +The segments in the URL, in following with the Model-View-Controller +approach, usually represent:: + + example.com/class/function/ID + + +#. The first segment represents the controller **class** that should be + invoked. +#. The second segment represents the class **function**, or method, that + should be called. +#. The third, and any additional segments, represent the ID and any + variables that will be passed to the controller. + +The :doc:`URI Class <../libraries/uri>` and the :doc:`URL Helper <../helpers/url_helper>` contain functions that make it +easy to work with your URI data. In addition, your URLs can be remapped +using the :doc:`URI Routing <routing>` feature for more flexibility. + +Removing the index.php file +=========================== + +By default, the **index.php** file will be included in your URLs:: + + example.com/index.php/news/article/my_article + +You can easily remove this file by using a .htaccess file with some +simple rules. Here is an example of such a file, using the "negative" +method in which everything is redirected except the specified items: + +:: + + RewriteEngine on + RewriteCond $1 !^(index\.php|images|robots\.txt) + RewriteRule ^(.*)$ /index.php/$1 [L] + +In the above example, any HTTP request other than those for index.php, +images, and robots.txt is treated as a request for your index.php file. + +Adding a URL Suffix +=================== + +In your **config/config.php** file you can specify a suffix that will be +added to all URLs generated by CodeIgniter. For example, if a URL is +this:: + + example.com/index.php/products/view/shoes + +You can optionally add a suffix, like **.html,** making the page appear to +be of a certain type:: + + example.com/index.php/products/view/shoes.html + +Enabling Query Strings +====================== + +In some cases you might prefer to use query strings URLs:: + + index.php?c=products&m=view&id=345 + +CodeIgniter optionally supports this capability, which can be enabled in +your **application/config.php** file. If you open your config file you'll +see these items:: + + $config['enable_query_strings'] = FALSE; + $config['controller_trigger'] = 'c'; + $config['function_trigger'] = 'm'; + +If you change "enable_query_strings" to TRUE this feature will become +active. Your controllers and functions will then be accessible using the +"trigger" words you've set to invoke your controllers and methods:: + + index.php?c=controller&m=method + +.. note:: If you are using query strings you will have to build + your own URLs, rather than utilizing the URL helpers (and other helpers + that generate URLs, like some of the form helpers) as these are designed + to work with segment based URLs. diff --git a/user_guide_src/source/general/views.rst b/user_guide_src/source/general/views.rst new file mode 100644 index 000000000..dc65f6c4f --- /dev/null +++ b/user_guide_src/source/general/views.rst @@ -0,0 +1,216 @@ +##### +Views +##### + +A view is simply a web page, or a page fragment, like a header, footer, +sidebar, etc. In fact, views can flexibly be embedded within other views +(within other views, etc., etc.) if you need this type of hierarchy. + +Views are never called directly, they must be loaded by a +:doc:`controller <controllers>`. Remember that in an MVC framework, the +Controller acts as the traffic cop, so it is responsible for fetching a +particular view. If you have not read the +:doc:`Controllers <controllers>` page you should do so before +continuing. + +Using the example controller you created in the +:doc:`controller <controllers>` page, let's add a view to it. + +Creating a View +=============== + +Using your text editor, create a file called blogview.php, and put this +in it:: + + <html> + <head> + <title>My Blog</title> + </head> + <body> + <h1>Welcome to my Blog!</h1> + </body> + </html> + +Then save the file in your application/views/ folder. + +Loading a View +============== + +To load a particular view file you will use the following function:: + + $this->load->view('name'); + +Where name is the name of your view file. Note: The .php file extension +does not need to be specified unless you use something other than .php. + +Now, open the controller file you made earlier called blog.php, and +replace the echo statement with the view loading function:: + + <?php + class Blog extends CI_Controller { + + function index() + { + $this->load->view('blogview'); + } + } + ?> + +If you visit your site using the URL you did earlier you should see your +new view. The URL was similar to this:: + + example.com/index.php/blog/ + +Loading multiple views +====================== + +CodeIgniter will intelligently handle multiple calls to +$this->load->view from within a controller. If more than one call +happens they will be appended together. For example, you may wish to +have a header view, a menu view, a content view, and a footer view. That +might look something like this:: + + <?php + + class Page extends CI_Controller { + + function index() + { + $data['page_title'] = 'Your title'; + $this->load->view('header'); + $this->load->view('menu'); + $this->load->view('content', $data); + $this->load->view('footer'); + } + + } + ?> + +In the example above, we are using "dynamically added data", which you +will see below. + +Storing Views within Sub-folders +================================ + +Your view files can also be stored within sub-folders if you prefer that +type of organization. When doing so you will need to include the folder +name loading the view. Example:: + + $this->load->view('folder_name/file_name'); + +Adding Dynamic Data to the View +=============================== + +Data is passed from the controller to the view by way of an **array** or +an **object** in the second parameter of the view loading function. Here +is an example using an array:: + + $data = array( + 'title' => 'My Title', + 'heading' => 'My Heading', + 'message' => 'My Message' + ); + + $this->load->view('blogview', $data); + +And here's an example using an object:: + + $data = new Someclass(); + $this->load->view('blogview', $data); + +Note: If you use an object, the class variables will be turned into +array elements. + +Let's try it with your controller file. Open it add this code:: + + <?php + class Blog extends CI_Controller { + + function index() + { + $data['title'] = "My Real Title"; + $data['heading'] = "My Real Heading"; + + $this->load->view('blogview', $data); + } + } + ?> + +Now open your view file and change the text to variables that correspond +to the array keys in your data:: + + <html> + <head> + <title><?php echo $title;?></title> + </head> + <body> + <h1><?php echo $heading;?></h1> + </body> + </html> + +Then load the page at the URL you've been using and you should see the +variables replaced. + +Creating Loops +============== + +The data array you pass to your view files is not limited to simple +variables. You can pass multi dimensional arrays, which can be looped to +generate multiple rows. For example, if you pull data from your database +it will typically be in the form of a multi-dimensional array. + +Here's a simple example. Add this to your controller:: + + <?php + class Blog extends CI_Controller { + + function index() + { + $data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands'); + + $data['title'] = "My Real Title"; + $data['heading'] = "My Real Heading"; + + $this->load->view('blogview', $data); + } + } + ?> + +Now open your view file and create a loop:: + + <html> + <head> + <title><?php echo $title;?></title> + </head> + <body> + <h1><?php echo $heading;?></h1> + + <h3>My Todo List</h3> + + <ul> + <?php foreach ($todo_list as $item):?> + + <li><?php echo $item;?></li> + + <?php endforeach;?> + </ul> + + </body> + </html> + +.. note:: You'll notice that in the example above we are using PHP's + alternative syntax. If you are not familiar with it you can read about + it :doc:`here </general/alternative_php>`. + +Returning views as data +======================= + +There is a third **optional** parameter lets you change the behavior of +the function so that it returns data as a string rather than sending it +to your browser. This can be useful if you want to process the data in +some way. If you set the parameter to true (boolean) it will return +data. The default behavior is false, which sends it to your browser. +Remember to assign it to a variable if you want the data returned:: + + $string = $this->load->view('myfile', '', true); + |