diff options
Diffstat (limited to 'user_guide_src')
-rw-r--r-- | user_guide_src/source/_themes/eldocs/layout.html | 3 | ||||
-rw-r--r-- | user_guide_src/source/changelog.rst | 1 | ||||
-rw-r--r-- | user_guide_src/source/conf.py | 2 | ||||
-rw-r--r-- | user_guide_src/source/general/controllers.rst | 9 | ||||
-rw-r--r-- | user_guide_src/source/general/helpers.rst | 37 | ||||
-rw-r--r-- | user_guide_src/source/general/index.rst | 3 | ||||
-rw-r--r-- | user_guide_src/source/general/models.rst | 6 | ||||
-rw-r--r-- | user_guide_src/source/general/security.rst | 4 | ||||
-rw-r--r-- | user_guide_src/source/general/urls.rst | 11 | ||||
-rw-r--r-- | user_guide_src/source/general/views.rst | 28 | ||||
-rw-r--r-- | user_guide_src/source/index.rst | 1 | ||||
-rw-r--r-- | user_guide_src/source/libraries/calendar.rst | 37 | ||||
-rw-r--r-- | user_guide_src/source/libraries/form_validation.rst | 1 | ||||
-rw-r--r-- | user_guide_src/source/tutorial/conclusion.rst | 26 | ||||
-rw-r--r-- | user_guide_src/source/tutorial/create_news_items.rst | 153 | ||||
-rw-r--r-- | user_guide_src/source/tutorial/index.rst | 47 | ||||
-rw-r--r-- | user_guide_src/source/tutorial/news_section.rst | 214 | ||||
-rw-r--r-- | user_guide_src/source/tutorial/static_pages.rst | 170 |
18 files changed, 677 insertions, 76 deletions
diff --git a/user_guide_src/source/_themes/eldocs/layout.html b/user_guide_src/source/_themes/eldocs/layout.html index ce54fa7ae..a79720ef1 100644 --- a/user_guide_src/source/_themes/eldocs/layout.html +++ b/user_guide_src/source/_themes/eldocs/layout.html @@ -124,7 +124,6 @@ {%- block footer %} <div id="footer"> - <p class="top"> {% if prev %} <span class="prev">Previous Topic: <a href="{{ prev.link }}">{{ prev.title }}</a></span> @@ -134,7 +133,7 @@ {% endif %} <a href="#header" title="Return to top">Return to top</a> </p> - <p><a href="{{ project_url }}">{{ project }}</a> – Copyright © {{ copyright }}</a></p> + <p><a href="{{ project_url }}">{{ project }}</a> – Copyright © {{ copyright }}</a> – Last updated: {{ last_updated }}</p> </div><!-- /#footer --> {%- endblock %} diff --git a/user_guide_src/source/changelog.rst b/user_guide_src/source/changelog.rst index f3e7cbbdd..925785d13 100644 --- a/user_guide_src/source/changelog.rst +++ b/user_guide_src/source/changelog.rst @@ -107,6 +107,7 @@ Bug fixes for 2.1.0 - Fixed a bug (#467) - Suppress warnings generated from get_magic_quotes_gpc() (deprecated in PHP 5.4) - Fixed a bug (#484) - First time _csrf_set_hash() is called, hash is never set to the cookie (in Security.php). - Fixed a bug (#60) - Added _file_mime_type() method to the `File Uploading Library <libraries/file_uploading>` in order to fix a possible MIME-type injection. +- Fixed a bug (#537) - Support for all wav type in browser. Version 2.0.3 ============= diff --git a/user_guide_src/source/conf.py b/user_guide_src/source/conf.py index cb28d21a1..bd5e65297 100644 --- a/user_guide_src/source/conf.py +++ b/user_guide_src/source/conf.py @@ -125,7 +125,7 @@ html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. diff --git a/user_guide_src/source/general/controllers.rst b/user_guide_src/source/general/controllers.rst index c3c19cc62..6e5079419 100644 --- a/user_guide_src/source/general/controllers.rst +++ b/user_guide_src/source/general/controllers.rst @@ -10,8 +10,8 @@ HTTP requests should be handled. What is a Controller? ===================== -A Controller is simply a class file that is named in a way that can be -associated with a URI. +**A Controller is simply a class file that is named in a way that can be +associated with a URI.** Consider this URI:: @@ -136,7 +136,7 @@ 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 +To specify a default controller, open your **application/config/routes.php** file and set this variable:: $route['default_controller'] = 'Blog'; @@ -199,8 +199,7 @@ 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::doc:`Views <views>` and `Output -class <../libraries/output>` pages. In some cases, however, you +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 diff --git a/user_guide_src/source/general/helpers.rst b/user_guide_src/source/general/helpers.rst index 71cb8b25a..3a98311a6 100644 --- a/user_guide_src/source/general/helpers.rst +++ b/user_guide_src/source/general/helpers.rst @@ -3,10 +3,10 @@ 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 +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 @@ -19,9 +19,9 @@ 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 +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. @@ -32,11 +32,11 @@ 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 +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:: +For example, to load the **URL Helper** file, which is named +**url_helper.php**, you would do this:: $this->load->helper('url'); @@ -63,9 +63,8 @@ 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. +initialization. This is done by opening the **application/config/autoload.php** +file and adding the helper to the autoload array. Using a Helper ============== @@ -84,8 +83,8 @@ 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\_ +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 - @@ -98,8 +97,8 @@ 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 +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 @@ -130,11 +129,11 @@ 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:: +**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\_ +Please note that all native CodeIgniter libraries are prefixed with **CI\_** so DO NOT use that as your prefix. Now What? diff --git a/user_guide_src/source/general/index.rst b/user_guide_src/source/general/index.rst index 2bc684a1d..1335e9dd4 100644 --- a/user_guide_src/source/general/index.rst +++ b/user_guide_src/source/general/index.rst @@ -4,6 +4,7 @@ General Topics .. toctree:: :titlesonly: + :hidden: urls controllers @@ -29,4 +30,4 @@ General Topics environments alternative_php security - PHP Style Guide <styleguide>
\ No newline at end of file + PHP Style Guide <styleguide> diff --git a/user_guide_src/source/general/models.rst b/user_guide_src/source/general/models.rst index 4dd3e5765..b816f958a 100644 --- a/user_guide_src/source/general/models.rst +++ b/user_guide_src/source/general/models.rst @@ -65,7 +65,7 @@ model class might look like:: Anatomy of a Model ================== -Model classes are stored in your application/models/ folder. They can be +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:: @@ -78,7 +78,7 @@ The basic prototype for a model class is this:: } } -Where Model_name is the name of your class. Class names **must** have +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. @@ -148,7 +148,7 @@ 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 +**application/config/autoload.php** file and adding the model to the autoload array. Connecting to your Database diff --git a/user_guide_src/source/general/security.rst b/user_guide_src/source/general/security.rst index d9d5b728b..4d7a213d1 100644 --- a/user_guide_src/source/general/security.rst +++ b/user_guide_src/source/general/security.rst @@ -35,8 +35,8 @@ 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 +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. diff --git a/user_guide_src/source/general/urls.rst b/user_guide_src/source/general/urls.rst index db1ffe565..211537675 100644 --- a/user_guide_src/source/general/urls.rst +++ b/user_guide_src/source/general/urls.rst @@ -28,8 +28,7 @@ approach, usually represent:: #. The third, and any additional segments, represent the ID and any variables that will be passed to the controller. -The :doc::doc:`URI Class <../libraries/uri>` and the `URL -Helper <../helpers/url_helper>` contain functions that make it +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. @@ -56,13 +55,13 @@ 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 +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 +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 @@ -75,7 +74,7 @@ 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 +your **application/config.php** file. If you open your config file you'll see these items:: $config['enable_query_strings'] = FALSE; @@ -88,7 +87,7 @@ active. Your controllers and functions will then be accessible using the index.php?c=controller&m=method -..note:: If you are using query strings you will have to build +.. 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 index 7d0accafd..dc65f6c4f 100644 --- a/user_guide_src/source/general/views.rst +++ b/user_guide_src/source/general/views.rst @@ -24,7 +24,7 @@ in it:: <html> <head> - <title>My Blog</title> + <title>My Blog</title> </head> <body> <h1>Welcome to my Blog!</h1> @@ -141,7 +141,7 @@ to the array keys in your data:: <html> <head> - <title><?php echo $title;?></title> + <title><?php echo $title;?></title> </head> <body> <h1><?php echo $heading;?></h1> @@ -180,27 +180,27 @@ Now open your view file and create a loop:: <html> <head> - <title><?php echo $title;?></title> + <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> + <h1><?php echo $heading;?></h1> + + <h3>My Todo List</h3> - <?php endforeach;?> - </ul> + <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 `here </general/alternative_php>`. + it :doc:`here </general/alternative_php>`. Returning views as data ======================= diff --git a/user_guide_src/source/index.rst b/user_guide_src/source/index.rst index b95161271..6cdeb2442 100644 --- a/user_guide_src/source/index.rst +++ b/user_guide_src/source/index.rst @@ -44,5 +44,6 @@ CodeIgniter is right for you if: helpers/index database/index documentation/index + tutorial/index general/quick_reference general/credits
\ No newline at end of file diff --git a/user_guide_src/source/libraries/calendar.rst b/user_guide_src/source/libraries/calendar.rst index 471fd64f9..3964db25e 100644 --- a/user_guide_src/source/libraries/calendar.rst +++ b/user_guide_src/source/libraries/calendar.rst @@ -86,28 +86,21 @@ The above code would start the calendar on saturday, use the "long" month heading, and the "short" day names. More information regarding preferences below. -+-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ -| Preference | Default | Options | Description | -+=======================+===========+===============================================+===================================================================+ -| **template** | None | None | A string containing your calendar template. | -| | | | See the template section below. | -+-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ -| **local_time** | time() | None | A Unix timestamp corresponding to the current time. | -+-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ -| **start_day** | sunday | Any week day (sunday, monday, tuesday, etc.) | Sets the day of the week the calendar should start on. | -+-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ -| **month_type** | long | long, short | Determines what version of the month name to use in the header. | -| | | | long = January, short = Jan. | -+-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ -| **day_type** | abr | long, short, abr | Determines what version of the weekday names to use in | -| | | | the column headers. | -| | | | long = Sunday, short = Sun, abr = Su. | -+-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ -| **show_next_prev** | FALSE | TRUE/FALSE (boolean) | Determines whether to display links allowing you to toggle | -| | | | to next/previous months. See information on this feature below. | -+-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ -| **next_prev_url** | None | A URL | Sets the basepath used in the next/previous calendar links. | -+-----------------------+-----------+-----------------------------------------------+-------------------------------------------------------------------+ +====================== =========== =============================================== =================================================================== +Preference Default Options Description +====================== =========== =============================================== =================================================================== +**template** None None A string containing your calendar template. + See the template section below. +**local_time** time() None A Unix timestamp corresponding to the current time. +**start_day** sunday Any week day (sunday, monday, tuesday, etc.) Sets the day of the week the calendar should start on. +**month_type** long long, short Determines what version of the month name to use in the header. + long = January, short = Jan. +**day_type** abr long, short, abr Determines what version of the weekday names to use in + the column headers. long = Sunday, short = Sun, abr = Su. +**show_next_prev** FALSE TRUE/FALSE (boolean) Determines whether to display links allowing you to toggle + to next/previous months. See information on this feature below. +**next_prev_url** None A URL Sets the basepath used in the next/previous calendar links. +====================== =========== =============================================== =================================================================== Showing Next/Previous Month Links diff --git a/user_guide_src/source/libraries/form_validation.rst b/user_guide_src/source/libraries/form_validation.rst index 53293ca5a..e7875bc22 100644 --- a/user_guide_src/source/libraries/form_validation.rst +++ b/user_guide_src/source/libraries/form_validation.rst @@ -823,7 +823,6 @@ Rule Reference The following is a list of all the native rules that are available to use: -.. table:: ======================= ========== ============================================================================================= ======================= Rule Parameter Description Example ======================= ========== ============================================================================================= ======================= diff --git a/user_guide_src/source/tutorial/conclusion.rst b/user_guide_src/source/tutorial/conclusion.rst new file mode 100644 index 000000000..48fbdcc8a --- /dev/null +++ b/user_guide_src/source/tutorial/conclusion.rst @@ -0,0 +1,26 @@ +########## +Conclusion +########## + +This tutorial did not cover all of the things you might expect of a +full-fledged content management system, but it introduced you to the +more important topics of routing, writing controllers, and models. We +hope this tutorial gave you an insight into some of CodeIgniter's basic +design patterns, which you can expand upon. + +Now that you've completed this tutorial, we recommend you check out the +rest of the documentation. CodeIgniter is often praised because of its +comprehensive documentation. Use this to your advantage and read the +"Introduction" and "General Topics" sections thoroughly. You should read +the class and helper references when needed. + +Every intermediate PHP programmer should be able to get the hang of +CodeIgniter within a few days. + +If you still have questions about the framework or your own CodeIgniter +code, you can: + +- Check out our `forums <http://codeigniter.com/forums>`_ +- Visit our `IRC chatroom <http://codeigniter.com/wiki/IRC>`_ +- Explore the `Wiki <http://codeigniter.com/wiki/>`_ + diff --git a/user_guide_src/source/tutorial/create_news_items.rst b/user_guide_src/source/tutorial/create_news_items.rst new file mode 100644 index 000000000..003b94bd8 --- /dev/null +++ b/user_guide_src/source/tutorial/create_news_items.rst @@ -0,0 +1,153 @@ +################# +Create news items +################# + +You now know how you can read data from a database using CodeIgnite, but +you haven't written any information to the database yet. In this section +you'll expand your news controller and model created earlier to include +this functionality. + +Create a form +------------- + +To input data into the database you need to create a form where you can +input the information to be stored. This means you'll be needing a form +with two fields, one for the title and one for the text. You'll derive +the slug from our title in the model. Create the new view at +application/views/news/create.php. + +:: + + <h2>Create a news item</h2> + + <?php echo validation_errors(); ?> + + <?php echo form_open('news/create') ?> + + <label for="title">Title</label> + <input type="input" name="title" /><br /> + + <label for="text">Text</label> + <textarea name="text"></textarea><br /> + + <input type="submit" name="submit" value="Create news item" /> + + </form> + +There are only two things here that probably look unfamiliar to you: the +form_open() function and the validation_errors() function. + +The first function is provided by the `form +helper <../helpers/form_helper.html>`_ and renders the form element and +adds extra functionality, like adding a hidden `CSFR prevention +field <../libraries/security.html>`_. The latter is used to report +errors related to form validation. + +Go back to your news controller. You're going to do two things here, +check whether the form was submitted and whether the submitted data +passed the validation rules. You'll use the `form +validation <../libraries/form_validation.html>`_ library to do this. + +:: + + public function create() + { + $this->load->helper('form'); + $this->load->library('form_validation'); + + $data['title'] = 'Create a news item'; + + $this->form_validation->set_rules('title', 'Title', 'required'); + $this->form_validation->set_rules('text', 'text', 'required'); + + if ($this->form_validation->run() === FALSE) + { + $this->load->view('templates/header', $data); + $this->load->view('news/create'); + $this->load->view('templates/footer'); + + } + else + { + $this->news_model->set_news(); + $this->load->view('news/success'); + } + } + +The code above adds a lot of functionality. The first few lines load the +form helper and the form validation library. After that, rules for the +form validation are set. The set\_rules() method takes three arguments; +the name of the input field, the name to be used in error messages, and +the rule. In this case the title and text fields are required. + +CodeIgniter has a powerful form validation library as demonstrated +above. You can read `more about this library +here <../libraries/form_validation.html>`_. + +Continuing down, you can see a condition that checks whether the form +validation ran successfully. If it did not, the form is displayed, if it +was submitted **and** passed all the rules, the model is called. After +this, a view is loaded to display a success message. Create a view at +application/view/news/success.php and write a success message. + +Model +----- + +The only thing that remains is writing a method that writes the data to +the database. You'll use the Active Record class to insert the +information and use the input library to get the posted data. Open up +the model created earlier and add the following: + +:: + + public function set_news() + { + $this->load->helper('url'); + + $slug = url_title($this->input->post('title'), 'dash', TRUE); + + $data = array( + 'title' => $this->input->post('title'), + 'slug' => $slug, + 'text' => $this->input->post('text') + ); + + return $this->db->insert('news', $data); + } + +This new method takes care of inserting the news item into the database. +The third line contains a new function, url\_title(). This function - +provided by the `URL helper <../helpers/url_helper.html>`_ - strips down +the string you pass it, replacing all spaces by dashes (-) and makes +sure everything is in lowercase characters. This leaves you with a nice +slug, perfect for creating URIs. + +Let's continue with preparing the record that is going to be inserted +later, inside the $data array. Each element corresponds with a column in +the database table created earlier. You might notice a new method here, +namely the post() method from the `input +library <../libraries/input.html>`_. This method makes sure the data is +sanitized, protecting you from nasty attacks from others. The input +library is loaded by default. At last, you insert our $data array into +our database. + +Routing +------- + +Before you can start adding news items into your CodeIgniter application +you have to add an extra rule to config/routes.php file. Make sure your +file contains the following. This makes sure CodeIgniter sees 'create' +as a method instead of a news item's slug. + +:: + + $route['news/create'] = 'news/create'; + $route['news/(:any)'] = 'news/view/$1'; + $route['news'] = 'news'; + $route['(:any)'] = 'pages/view/$1'; + $route['default_controller'] = 'pages/view'; + +Now point your browser to your local development environment where you +installed CodeIgniter and add index.php/news/create to the URL. +Congratulations, you just created your first CodeIgniter application! +Add some news and check out the different pages you made. diff --git a/user_guide_src/source/tutorial/index.rst b/user_guide_src/source/tutorial/index.rst new file mode 100644 index 000000000..eb6f11e34 --- /dev/null +++ b/user_guide_src/source/tutorial/index.rst @@ -0,0 +1,47 @@ +######## +Tutorial +######## + +This tutorial is intended to introduce you to the CodeIgniter framework +and the basic principles of MVC architecture. It will show you how a +basic CodeIgniter application is constructed in step-by-step fashion. + +In this tutorial, you will be creating a **basic news application**. You +will begin by writing the code that can load static pages. Next, you +will create a news section that reads news items from a database. +Finally, you'll add a form to create news items in the database. + +This tutorial will primarily focus on: + +- Model-View-Controller basics +- Routing basics +- Form validation +- Performing basic database queries using "Active Record" + +The entire tutorial is split up over several pages, each explaining a +small part of the functionality of the CodeIgniter framework. You'll go +through the following pages: + +- Introduction, this page, which gives you an overview of what to + expect. +- `Static pages <static_pages.html>`_, which will teach you the basics + of controllers, views and routing. +- `News section <news_section.html>`_, where you'll start using models + and will be doing some basic database operations. +- `Create news items <create_news_items.html>`_, which will introduce + more advanced database operations and form validation. +- `Conclusion <conclusion.html>`_, which will give you some pointers on + further reading and other resources. + +Enjoy your exploration of the CodeIgniter framework. + +.. toctree:: + :glob: + :hidden: + :titlesonly: + + index + static_pages + news_section + create_news_items + conclusion
\ No newline at end of file diff --git a/user_guide_src/source/tutorial/news_section.rst b/user_guide_src/source/tutorial/news_section.rst new file mode 100644 index 000000000..fe8e41607 --- /dev/null +++ b/user_guide_src/source/tutorial/news_section.rst @@ -0,0 +1,214 @@ +############ +News section +############ + +In the last section, we went over some basic concepts of the framework +by writing a class that includes static pages. We cleaned up the URI by +adding custom routing rules. Now it's time to introduce dynamic content +and start using a database. + +Setting up your model +--------------------- + +Instead of writing database operations right in the controller, queries +should be placed in a model, so they can easily be reused later. Models +are the place where you retrieve, insert, and update information in your +database or other data stores. They represent your data. + +Open up the application/models directory and create a new file called +news_model.php and add the following code. Make sure you've configured +your database properly as described +`here <../database/configuration.html>`_. + +:: + + <?php + class News_model extends CI_Model { + + public function __construct() + { + $this->load->database(); + } + } + +This code looks similar to the controller code that was used earlier. It +creates a new model by extending CI\_Model and loads the database +library. This will make the database class available through the +$this->db object. + +Before querying the database, a database schema has to be created. +Connect to your database and run the SQL command below. Also add some +seed records. + +:: + + CREATE TABLE news ( + id int(11) NOT NULL AUTO_INCREMENT, + title varchar(128) NOT NULL, + slug varchar(128) NOT NULL, + text text NOT NULL, + PRIMARY KEY (id), + KEY slug (slug) + ); + +Now that the database and a model have been set up, you'll need a method +to get all of our posts from our database. To do this, the database +abstraction layer that is included with CodeIgniter — `Active +Record <../database/active_record.html>`_ — is used. This makes it +possible to write your 'queries' once and make them work on `all +supported database systems <../general/requirements.html>`_. Add the +following code to your model. + +:: + + public function get_news($slug = FALSE) + { + if ($slug === FALSE) + { + $query = $this->db->get('news'); + return $query->result_array(); + } + + $query = $this->db->get_where('news', array('slug' => $slug)); + return $query->row_array(); + } + +With this code you can perform two different queries. You can get all +news records, or get a news item by its `slug <#>`_. You might have +noticed that the $slug variable wasn't sanitized before running the +query; Active Record does this for you. + +Display the news +---------------- + +Now that the queries are written, the model should be tied to the views +that are going to display the news items to the user. This could be done +in our pages controller created earlier, but for the sake of clarity, a +new "news" controller is defined. Create the new controller at +application/controllers/news.php. + +:: + + <?php + class News extends CI_Controller { + + public function __construct() + { + parent::__construct(); + $this->load->model('news_model'); + } + + public function index() + { + $data['news'] = $this->news_model->get_news(); + } + + public function view($slug) + { + $data['news'] = $this->news_model->get_news($slug); + } + } + +Looking at the code, you may see some similarity with the files we +created earlier. First, the "\_\_construct" method: it calls the +constructor of its parent class (CI\_Controller) and loads the model, so +it can be used in all other methods in this controller. + +Next, there are two methods to view all news items and one for a +specific news item. You can see that the $slug variable is passed to the +model's method in the second method. The model is using this slug to +identify the news item to be returned. + +Now the data is retrieved by the controller through our model, but +nothing is displayed yet. The next thing to do is passing this data to +the views. + +:: + + public function index() + { + $data['news'] = $this->news_model->get_news(); + $data['title'] = 'News archive'; + + $this->load->view('templates/header', $data); + $this->load->view('news/index', $data); + $this->load->view('templates/footer'); + } + +The code above gets all news records from the model and assigns it to a +variable. The value for the title is also assigned to the $data['title'] +element and all data is passed to the views. You now need to create a +view to render the news items. Create application/views/news/index.php +and add the next piece of code. + +:: + + <?php foreach ($news as $news_item): ?> + + <h2><?php echo $news_item['title'] ?></h2> + <div id="main"> + <?php echo $news_item['text'] ?> + </div> + <p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p> + + <?php endforeach ?> + +Here, each news item is looped and displayed to the user. You can see we +wrote our template in PHP mixed with HTML. If you prefer to use a +template language, you can use CodeIgniter's `Template +Parser <../libraries/parser.html>`_ class or a third party parser. + +The news overview page is now done, but a page to display individual +news items is still absent. The model created earlier is made in such +way that it can easily be used for this functionality. You only need to +add some code to the controller and create a new view. Go back to the +news controller and add the following lines to the file. + +:: + + public function view($slug) + { + $data['news_item'] = $this->news_model->get_news($slug); + + if (empty($data['news_item'])) + { + show_404(); + } + + $data['title'] = $data['news_item']['title']; + + $this->load->view('templates/header', $data); + $this->load->view('news/view', $data); + $this->load->view('templates/footer'); + } + +Instead of calling the get\_news() method without a parameter, the $slug +variable is passed, so it will return the specific news item. The only +things left to do is create the corresponding view at +application/views/news/view.php. Put the following code in this file. + +:: + + <?php + echo '<h2>'.$news_item['title'].'</h2>'; + echo $news_item['text']; + +Routing +------- + +Because of the wildcard routing rule created earlier, you need need an +extra route to view the controller that you just made. Modify your +routing file (application/config/routes.php) so it looks as follows. +This makes sure the requests reaches the news controller instead of +going directly to the pages controller. The first line routes URI's with +a slug to the view method in the news controller. + +:: + + $route['news/(:any)'] = 'news/view/$1'; + $route['news'] = 'news'; + $route['(:any)'] = 'pages/view/$1'; + $route['default_controller'] = 'pages/view'; + +Point your browser to your document root, followed by index.php/news and +watch your news page. diff --git a/user_guide_src/source/tutorial/static_pages.rst b/user_guide_src/source/tutorial/static_pages.rst new file mode 100644 index 000000000..0bbf51b1b --- /dev/null +++ b/user_guide_src/source/tutorial/static_pages.rst @@ -0,0 +1,170 @@ +############ +Static pages +############ + +**Note:** This tutorial assumes you've downloaded CodeIgniter and +`installed the framework <../installation/index.html>`_ in your +development environment. + +The first thing you're going to do is set up a **controller** to handle +static pages. A controller is simply a class that helps delegate work. +It is the glue of your web application. + +For example, when a call is made to: +``http://example.com/news/latest/10`` We might imagine that there is a +controller named "news". The method being called on news would be +"latest". The news method's job could be to grab 10 news items, and +render them on the page. Very often in MVC, you'll see URL patterns that +match: +``http://example.com/[controller-class]/[controller-method]/[arguments]`` +As URL schemes become more complex, this may change. But for now, this +is all we will need to know. + +Create a file at application/controllers/pages.php with the following +code. + +:: + + <?php + class Pages extends CI_Controller { + + public function view($page == 'home') + { + + } + + } + +You have created a class named "pages", with a view method that accepts +one argument named $page. The pages class is extending the +CI_Controller class. This means that the new pages class can access the +methods and variables defined in the CI_Controller class +(system/core/Controller.php). + +The **controller is what will become the center of every request** to +your web application. In very technical CodeIgniter discussions, it may +be referred to as the *super object*. Like any php class, you refer to +it within your controllers as $this. Referring to $this is how you will +load libraries, views, and generally command the framework. + +Now you've created your first method, it's time to make some basic page +templates. We will be creating two "views" (page templates) that act as +our page footer and header. + +Create the header at application/views/templates/header.php and add the +following code. + +:: + + <html> + <head> + <title>CodeIgniter 2 Tutorial</title> + </head> + <body> + + <h1>CodeIgniter 2 Tutorial<h1> + +The header contains the basic HTML code that you'll want to display +before loading the main view, together with a heading. It will also +output the $title variable, which we'll define later in the controller. +Now create a footer at application/views/templates/footer.php that +includes the following code: + +:: + + <em>© 2011</em> + </body> + <html> + +Adding logic to the controller +------------------------------ + +Earlier you set up a controller with a view() method. The method accepts +one parameter, which is the name of the page to be loaded. The static +page templates will be located in the application/views/pages/ +directory. + +In that directory, create two files named home.php and about.php. Within +those files, type some text − anything you'd like − and save them. If +you like to be particularly un-original, try "Hello World!". + +In order to load those pages, you'll have to check whether the requested +page actually exists: + +:: + + <?php + public function view($page = 'home') + { + + if ( ! file_exists('application/views/pages/'.$page.'.php')) + { + // Whoops, we don't have a page for that! + show_404(); + } + + $data['title'] = ucfirst($page); // Capitalize the first letter + + $this->load->view('templates/header', $data); + $this->load->view('pages/'.$page, $data); + $this->load->view('templates/footer', $data); + + } + +Now, when the page does exist, it is loaded, including the header and +footer, and displayed to the user. If the page doesn't exist, a "404 +Page not found" error is shown. + +The first line in this method checks whether the page actually exists. +PHP's native file\_exists() function is used to check whether the file +is where it's expected to be. show\_404() is a built-in CodeIgniter +function that renders the default error page. + +In the header template, the $title variable was used to customize the +page title. The value of title is defined in this method, but instead of +assigning the value to a variable, it is assigned to the title element +in the $data array. + +The last thing that has to be done is loading the views in the order +they should be displayed. The second parameter in the view() method is +used to pass values to the view. Each value in the $data array is +assigned to a variable with the name of its key. So the value of +$data['title'] in the controller is equivalent to $title in the view. + +Routing +------- + +The controller is now functioning! Point your browser to +[your-site-url]index.php/pages/view to see your page. When you visit +index.php/pages/view/about you'll see the about page, again including +the header and footer. + +Using custom routing rules, you have the power to map any URI to any +controller and method, and break free from the normal convention: +``http://example.com/[controller-class]/[controller-method]/[arguments]`` + +Let's do that. Open the routing file located at +application/config/routes.php and add the following two lines. Remove +all other code that sets any element in the $route array. + +:: + + $route['default_controller'] = 'pages/view'; + $route['(:any)'] = 'pages/view/$1'; + +CodeIgniter reads its routing rules from top to bottom and routes the +request to the first matching rule. Each rule is a regular expression +(left-side) mapped to a controller and method name separated by slashes +(right-side). When a request comes in, CodeIgniter looks for the first +match, and calls the appropriate controller and method, possibly with +arguments. + +More information about routing can be found in the URI Routing +`documentation <../general/routing.html>`_. + +Here, the second rule in the $routes array matches **any** request using +the wildcard string (:any). and passes the parameter to the view() +method of the pages class. + +Now visit index.php/about. Did it get routed correctly to the view() +method in the pages controller? Awesome! |