Tutorial de CodeIgniter

download Tutorial de CodeIgniter

of 27

Transcript of Tutorial de CodeIgniter

  • 8/10/2019 Tutorial de CodeIgniter

    1/27

    CodeIgniter Tutorial Learn

    CodeIgniter in 40 minutes

    http://www.revillweb.com/tutorials/codeigniter-tutorial-learn-

    codeigniter-in-40-minutes/

    * can also be renamed or relocated anywhere on your server. If

    * you do, use a full server path. or more info please see the user

    guide:

    * http://codeigniter.com/user!guide/general/managing!apps.html

    *

    * "# $%&I'I"( )'&)+

    *

    */

    application!folder application

    $system_pathand $application_folderis where codeigniter will look for the

    respective folders, you need to update this file so that it is pointing to where you

    moved the applicationand systemfolder. Change this file to read the

    following:

    /*

    *---------------------------------------------------------------

    * ))$12 #'31% "&21

    *---------------------------------------------------------------

    *

    * $his variable must contain the name of your system folder.

    * Include the path if the folder is not in the same directory

    * as this file.*

    http://www.revillweb.com/tutorials/codeigniter-tutorial-learn-codeigniter-in-40-minutes/http://www.revillweb.com/tutorials/codeigniter-tutorial-learn-codeigniter-in-40-minutes/http://www.revillweb.com/tutorials/codeigniter-tutorial-learn-codeigniter-in-40-minutes/http://www.revillweb.com/tutorials/codeigniter-tutorial-learn-codeigniter-in-40-minutes/
  • 8/10/2019 Tutorial de CodeIgniter

    2/27

    */

    system!path ../codeigniter/system

    /*

    *---------------------------------------------------------------

    * &55'I6&$I#" #'31% "&21

    *---------------------------------------------------------------

    *

    * If you want this front controller to use a different application

    * folder then the default one you can set its name here. $he folder

    * can also be renamed or relocated anywhere on your server. If

    * you do, use a full server path. or more info please see the user

    guide:

    * http://codeigniter.com/user!guide/general/managing!apps.html

    *

    * "# $%&I'I"( )'&)+

    *

    */

    application!folder ../codeigniter/application

    To remove index.phpfrom the URL we also need to create a .htaccessfile

    with the following contents:

    %ewrite1ngine on

    %ewrite6ond 7 +89inde;.php

  • 8/10/2019 Tutorial de CodeIgniter

    3/27

    file/codeigniter/application/config/autoload.php. $rom line )* you should

    see the following:

    /*

    default?>password? >5&))#%3?

    db>default?>database? tutorial

    db>default?>dbdriver? mysHl

    db>default?>dbprefi?

    db>default?>pconnect? $%D1

    db>default?>db!debug? $%D1db>default?>cache!on? &')1

    db>default?>cachedir?

    db>default?>char!set? utfE

    db>default?>dbcollat? utfE!general!ci

    db>default?>swap!pre?

    db>default?>autoinit? $%D1

    db>default?>stricton? &')1

    ow that Code/gniter knows how to access our dataase and user tale, we

    can no go ahead and create a model which will represent a user.

    /**

    * Includes the Dser!2odel class as well as the reHuired sub-classes

    * JpacKage codeigniter.application.models*/

    /**

    * Dser!2odel etends codeigniters base 6I!2odel to inherit all

    codeigniter magic+

    * Jauthor 'eon %evill

    * JpacKage codeigniter.application.models

    */

    classDser!2odeletends6I!2odel

  • 8/10/2019 Tutorial de CodeIgniter

    8/27

    L

    /*

    * & private variable to represent each column in the database

    */

    private!id

    private!username

    private!password

    function !!construct9=

    L

    parent::!!construct9=

    M

    /*

    * )1$s N (1$s

    * )ets and gets allow you to retrieve or set a private

    variable on an obOect

    */

    /**

    I3

    **/

    /**

    * Jreturn int >this-P!id? %eturn this obOects I3

    */

    publicfunction getId9=L

    returnthis-P!id

    M

    /**

    * Jparam int Integer to set this obOects I3 to

    */

    publicfunction setId9value=L

  • 8/10/2019 Tutorial de CodeIgniter

    9/27

    this-P!id value

    M

    /**

    D)1%"&21

    **/

    /**

    * Jreturn string >this-P!username? %eturn this obOects

    username

    */

    publicfunction getDsername9=

    L

    returnthis-P!username

    M

    /**

    * Jparam string )tring to set this obOects username to

    */

    publicfunction setDsername9value=

    L

    this-P!username value

    M

    /**

    5&))#%3

    **/

    /**

    * Jreturn string >this-P!password? %eturn this obOects

    password

    */

    publicfunction get5assword9=

    L

    returnthis-P!password

    M

  • 8/10/2019 Tutorial de CodeIgniter

    10/27

    /**

    * Jparam string )tring to set this obOects password to

    */

    publicfunction set5assword9value=

    L

    this-P!password value

    M

    /*

    * 6lass 2ethods

    */

    /**

    * 6ommit method, this will comment the entire obOect to

    the database

    */

    publicfunction commit9=

    L

    data array9

    usernameP this-P!username,

    passwordP this-P!password

    =

    if9this-P!id P 0= L

    //e have an I3 so we need to update this

    obOect because it is not new

    if9this-Pdb-Pupdate9user, data, array9id

    P this-P!id=== Lreturntrue

    M

    M elseL

    //e dont have an I3 meaning it is new and not

    yet in the database so we need to do an insert

    if9this-Pdb-Pinsert9user, data== L

    //"ow we can get the I3 and update the

    newly created obOectthis-P!id this-Pdb-Pinsert!id9=

  • 8/10/2019 Tutorial de CodeIgniter

    11/27

    returntrue

    M

    M

    returnfalse

    M

    M

    Save the aove code as a file called user_model.phpwithin

    the/codeigniter/application/modelsdirectory.

    +nd that is all there is to a model- The aove code is well commented andshould make sense ut lets go over it section y section. Lets start with the

    private variales.

    R/1+T@ 1+R/+7L@S

    private !id

    private !username

    private !password

    These variales simple provide a place for us to store the data from their

    matching column in the dataase, you can call them anything you like ut it

    makes sense to call them the same thing as the dataase column to avoid

    confusion.

    S@TS A B@TS

    public function getDsername9=

    L

    return this-P!id

    M

  • 8/10/2019 Tutorial de CodeIgniter

    12/27

    public function setDsername9value=

    L

    this-P!username value

    M

    ou can look at sets and gets as an interface to the o2ect that the model is

    representing. =e have private variales as opposed to pulic so that they

    cannot e modified outside the models scope. This allows us to use set and get

    methods to control what can e set and what can e got from these private

    variales. $or e9ample, you could always cast to integer to ensure that a private

    variale would always e so, something you could not do if you were e9posing

    the local variales to the outside world. +nother e9ample is if one of these

    private variales was a date, you could ensure that a formatted date was

    always provided via the get method for this variale, saving formatting the value

    every time you needed it.

    C(00/T/B T4@ (7D@CT

    public function commit9=

    L

    data array9

    username P this-P!username,

    password P this-P!password

    =

    if 9this-P!id P 0= L

    //e have an I3 so we need to update this

    obOect because it is not new

    if 9this-Pdb-Pupdate9user, data, array9id

    P this-P!id=== L

    return true

    M

    M else L

  • 8/10/2019 Tutorial de CodeIgniter

    13/27

    //e dont have an I3 meaning it is new and not

    yet in the database so we need to do an insert

    if 9this-Pdb-Pinsert9user, data== L

    //"ow we can get the I3 and update the

    newly created obOect

    this-P!id this-Pdb-Pinsert!id9=

    return true

    M

    M

    return false

    M

    (viously at some point we are going to want to save the o2ect&s data ack to

    the dataase. =e create a method called commit which simply does that. This

    method checks to see if it has an />, if it does then an entry for this o2ect

    already e9ists within the dataase. /f the o2ect already e9ists in the dataase

    then it needs to perform an update. /f the o2ect doesn&t already have an /> then

    it does not currently have a dataase entry. /f there is no entry it needs to create

    a new one and then, using the myS8L function insert_id!which returns the />

    of the last inserted row# to then update the o2ect so it will then only perform

    updates and not insert a new entry every time a commit is performed.

    0(>@L $+CT(R

    =e are going to create a very simple factory which is asically a collection of

    methods within a lirary that we can reuse to create o2ects with our model.

    This separates out methods such as getUser, createUser, etcfrom within the

    model, ensuring that the model can strictly represent the dataase row. Take a

    look at the following code:

    if 9 + defined9A&)15&$== eit9"o direct script access allowed=

    class Dseractory L

  • 8/10/2019 Tutorial de CodeIgniter

    14/27

    private !ci

    function !!construct9=

    L

    //hen the class is constructed get an instance of codeigniter

    so we can access it locally

    this-P!ci N get!instance9=

    //Include the user!model so we can use it

    this-P!ci-Pload-Pmodel9user!model=

    M

    public function getDser9id 0= L

    //&re we getting an individual user or are we getting them all

    if 9id P 0= L

    //(etting an individual user

    Huery this-P!ci-Pdb-Pget!where9user, array9id

    P id==

    //6hecK if any results were returned

    if 9Huery-Pnum!rows9= P 0= L

    //5ass the data to our local function to create

    an obOect for us and return this new obOect

    return this-Pcreate#bOectrom3ata9Huery-

    Prow9==

    M

    return false

    M else L

    //(etting all the users Huery this-P!ci-Pdb-Pselect9*=-Pfrom9user=-

    Pget9=

    //6hecK if any results were returned

    if 9Huery-Pnum!rows9= P 0= L

    //6reate an array to store users

    users array9=

    //'oop through each row returned from the Huery

    foreach 9Huery-Presult9= as row= L

  • 8/10/2019 Tutorial de CodeIgniter

    15/27

  • 8/10/2019 Tutorial de CodeIgniter

    16/27

    L

    //hen the class is constructed get an instance of codeigniter

    so we can access it locally

    this-P!ci N get!instance9=

    //Include the user!model so we can use it

    this-P!ci-Pload-Pmodel9user!model=

    M

    4ere we are creating a private variale called $_ci, short for codeigniterwhich

    is where we are going to store an instance of codeigniterso we have access to

    all its resources. The reason codeigniteris like this is ecause you may want

    to create liraries that do not re'uire any of the codeigniterfunctionality

    therefore why include the e9tra ulkE Codeigniteris very lean rememer-

    Learn more aout creating liraries in codeigniterhere.

    Then, within the__construct!of the lirary !which is called when the class is

    instantiated# we gra this codeigniterinstance and store it in this variale. ow

    we can access all of codeigniter&s magic, for e9ample: $this"#_ci"#db"

    #select%&!"#fromuser&!"#get!'

    =e have two methods within our factory, the main method is get user:

    public function getDser9id 0= L

    //&re we getting an individual user or are we getting them all

    if 9id P 0= L

    //(etting an individual user

    Huery this-P!ci-Pdb-Pget!where9user, array9id

    P id==

    //6hecK if any results were returned

    if 9Huery-Pnum!rows9= P 0= L

    //5ass the data to our local function to create

    an obOect for us and return this new obOect

    return this-Pcreate#bOectrom3ata9Huery-

    Prow9==

    http://ellislab.com/codeigniter/user-guide/general/creating_libraries.htmlhttp://ellislab.com/codeigniter/user-guide/general/creating_libraries.html
  • 8/10/2019 Tutorial de CodeIgniter

    17/27

    M

    return false

    M else L

    //(etting all the users

    Huery this-P!ci-Pdb-Pselect9*=-Pfrom9user=-

    Pget9=

    //6hecK if any results were returned

    if 9Huery-Pnum!rows9= P 0= L

    //6reate an array to store users

    users array9=

    //'oop through each row returned from the Huery

    foreach 9Huery-Presult9= as row= L

    //5ass the row data to our local

    function which creates a new user obOect with the data provided and

    add it to the users array

    users>? this-

    Pcreate#bOectrom3ata9row=

    M

    //%eturn the users array

    return users

    M

    return false

    M

    M

    This method allows us to pass a parameter of $idso we can retrieve a specific

    user o2ect, or if we do not provide an /> it will get all of the user o2ects for us.Lets walk through the more complicated side of this method, getting all users:

    //(etting all the users

    Huery this-P!ci-Pdb-Pselect9*=-Pfrom9user=-Pget9=

    //6hecK if any results were returned

    if 9Huery-Pnum!rows9= P 0= L

    //6reate an array to store users

    users array9=

  • 8/10/2019 Tutorial de CodeIgniter

    18/27

    //'oop through each row returned from the Huery

    foreach 9Huery-Presult9= as row= L

    //5ass the row data to our local function which

    creates a new user obOect with the data provided and add it to the

    users array

    users>? this-Pcreate#bOectrom3ata9row=

    M

    //%eturn the users array

    return users

    M

    return false

    $irstly we 'uery the user tale and return all rows !$(uery ) $this"#_ci"#db"

    #select%&!"#fromuser&!"#get!'#. =e then check to see if there are any

    results using the $(uery"#num_rows!method which will return the numer of

    results. /f the numer is F then we return false and end e9ecution. /f the numer

    of rows is greater than F then we create an array called usersand then loop

    through every row returned in the 'uery: foreach $(uery"#result! as $row! *.

    $or each returned row we then call our local method:

    public function create#bOectrom3ata9row= L

    //6reate a new user!model obOect

    user new Dser!2odel9=

    //)et the I3 on the user model

    user-PsetId9row-Pid=

    //)et the username on the user model

    user-PsetDsername9row-Pusername=

    //)et the password on the user model

    user-Pset5assword9row-Ppassword=

    //%eturn the new user obOect

    return user

    M

  • 8/10/2019 Tutorial de CodeIgniter

    19/27

    This method takes the row data and creates a new user o2ect using the

    user"model class we created earlier. /t then sets the appropriate values from

    the dataase row onto this o2ect and then returns the o2ect to the calling

    method.

    (nce the calling method receives the new o2ect it adds it to the $usersarray.

    (nce it has iterated through each of the returned rows it returns

    the $usersarray. Simple-

    ow we have a way of representing a dataase row using a model and a way to

    get a set of o2ects represented y the codeignitermodel using a lirary, letsmove on to something you can see-

    +lease note that the user factory needs to be saed within

    the/codeigniter/application/librariesdirectory.

    CONTROLLERS

    + controller decides what to display and how to display it. =ithin

    the/codeingiter/application/controllerscreate a file called users, which looks

    like this:

    if 9 + defined9A&)15&$== eit9"o direct script access allowed=

    class Dsers etends 6I!6ontroller L

    public function inde9=

    L

    echo $his is the inde+

    M

    public function show9userId 0=

    L

    userId 9int=userId

  • 8/10/2019 Tutorial de CodeIgniter

    20/27

    echo $his is show users+

    if 9userId P 0= L

    echo Dser I3: LuserIdM

    M

    M

    M

    This is not the final version of our controller, we are 2ust going to use this to

    demonstrate and help you understand how the controllers in codeigniterwork.

    /f you navigate to your site, lets say the URL you are using

    is http-//localhost-/, then navigate to: http-//localhost-/usersand

    you should see the following:

    The indexmethod within the controller is what the controller will fall ack on if

    there has een no other method specified within the URL, so ecause we 2ust

    went to/usersthe inde9 method is called. ow, navigate

    to: http-//localhost-/users/showand you should see the following:

  • 8/10/2019 Tutorial de CodeIgniter

    21/27

    4ere you can see that y specifying showas the second URL section we are

    calling the show method within the controller. ow, navigate

    to: http-//localhost-/users/show/0and see the following:

    =ith the third section we have passed in a user /> which the show method

    picks up and displays on the screen. =e can pass any numer of parameters to

    a codeignitercontroller method. ow you understand

    how codeigniterscontrollers work we can move on and make the users

    controller a little more practical.

    Change the show method to look like elow:

    public function show9userId 0=

    L

    //&lways ensure an integer

    userId 9int=userId

  • 8/10/2019 Tutorial de CodeIgniter

    22/27

    //'oad the user factory

    this-Pload-Plibrary9Dseractory=

    //6reate a data array so we can pass information to the

    view

    data array9

    users P this-Puserfactory-PgetDser9userId=

    =

    //3ump out the data array

    var!dump9data=

    M

    +s always the code is well commented so it should e easy to follow. The main

    thing that this method is doing now, is loading the user factory so we can

    retrieve user o2ects using the lirary and model we created earlier. =e store

    the results within an array which we will eventually pass to a view and then 2ust

    for now we are dumping the results so we can see how they look. Bo ahead

    and navigate to: http-//localhost-/users/showand you should see the

    following:

    array97= L >users?P array94= L >0?P obOect9Dser!2odel=QCC 9R=

    L >!id:Dser!2odel:private?P string97= 7

    >!username:Dser!2odel:private?P string9S= (andalf

    >!password:Dser!2odel:private?P string9T= iamwhite+ M >7?P

    obOect9Dser!2odel=QCR 9R= L >!id:Dser!2odel:private?P string97=

    C >!username:Dser!2odel:private?P string9U= Ailbo

    >!password:Dser!2odel:private?P string970= bagginses+ M >C?P

    obOect9Dser!2odel=QC4 9R= L >!id:Dser!2odel:private?P string97=

    R >!username:Dser!2odel:private?P string9V= (ollum

    >!password:Dser!2odel:private?P string9E= precious M >R?P

    obOect9Dser!2odel=QCU 9R= L >!id:Dser!2odel:private?P string97=

    4 >!username:Dser!2odel:private?P string9U= arwen

    >!password:Dser!2odel:private?P string97U=

    tolodannangalad M M M

  • 8/10/2019 Tutorial de CodeIgniter

    23/27

    The aove output is a dump of an array of user models which are presenting

    every user within our user tale, if you navigate

    to: http-//localhost-/users/show/0and view the following output:

    array97= L >users?P obOect9Dser!2odel=Q7T 9R=

    L >!id:Dser!2odel:private?P string97= 7

    >!username:Dser!2odel:private?P string9S= (andalf

    >!password:Dser!2odel:private?P string9T= iamwhite+ M M

    ou can see that the results are 2ust for the user with user /> ; as this is whatwe have specified within the URL, try changing the user /> and see what

    happens.

    ow you should have a pretty good understanding as to how we can re'uest

    and retrieve data from the dataase in a complete o2ect oriented manner. Lets

    move onto the final section and create some views-

    VIEWS

    + view is simple how the data is presented to the user, typically consisting of the

    4T0L and other client side code. =e are going to create a view which will take

    the data array we created in our controller in the previous section and list out all

    the users it is given. =ithin/codeingiter/application/iewscreate a file

    called show_users.phpwith the following code:

    //6hecK to see if users could be found

    if 9users + &')1= L

    //6reate the $2' table header

    echo WWW$2'

    Wtable border7P

  • 8/10/2019 Tutorial de CodeIgniter

    24/27

    WtrP

    WthPI3 QW/thP

    WthPDsernameW/thP

    WthP5asswordW/thP

    W/trP

    $2'

    //3o we have an array of users or Oust a single user

    obOectX

    if 9is!array9users= NN count9users== L

    //'oop through all the users and create a row

    for each within the table

    foreach 9users as user= L

    echo WWW$2'

    WtrP

    WtdPLuser-PgetId9=MW/tdP

    WtdPLuser-

    PgetDsername9=MW/tdP

    WtdPLuser-

    Pget5assword9=MW/tdP

    W/trP

    $2'

    M

    M else L

    //#nly a single user obOect so Oust create onerow within the table

    echo WWW$2'

    WtrP

    WtdPLusers-

    PgetId9=MW/tdP

    WtdPLusers-

    PgetDsername9=MW/tdP

  • 8/10/2019 Tutorial de CodeIgniter

    25/27

    WtdPLusers-

    Pget5assword9=MW/tdP

    W/trP

    $2'

    M

    //6lose the table $2'

    echo WWW$2'

    W/tableP

    $2'

    M else L

    //"ow user could be found so display an error messsage

    to the user

    echo WWW$2'

    WpP& user could not be found with the specified

    user I3Q, please try again.W/pP

    $2'

    M

    7efore we take a look at this code in any detail, we need to update our

    controller to load the view and provide it with the user data it needs. Change the

    show method within the users controller to e as follows:

    public function show9userId 0=

    L

    //&lways ensure an integer

    userId 9int=userId

    //'oad the user factory

    this-Pload-Plibrary9Dseractory=

    //6reate a data array so we can pass information to the

    view

    data array9

  • 8/10/2019 Tutorial de CodeIgniter

    26/27

    users P this-Puserfactory-PgetDser9userId=

    =

    //'oad the view and pass the data to it

    this-Pload-Pview9show!users, data=

    M

    +ll we have changed is we are now using this codeigniterload functionality

    !$this"#load"#iew!# to load the view we have created. The first parameter is

    the name of the file within the views directory we want to load, the second is an

    array of data we want to pass to the view. ote that any key within

    the $dataarray will ecome a variale within the view. So in this e9ample to

    access the $data12users23value, we simple use $userswithin the view.

    ow we have the controller loading the view and we understand how to access

    the data we have passed to it from within the view, lets walk through the code.

    $irstly we check to see if the Gusers variale is not false, if the factory cannot

    find a user with the specified /> then it will return false. =e handle this and then

    display an error message to the user: 5+ user could not e found with the

    specified user />H, please try again.6.

    /f the Gusers variale is not false and has some data we then need to check to

    see if it is a single user !an /> has een specified# or it is an array of multiple

    users. /f it is multiple users we then loop through each user and create a row

    with their data within the 4T0L tale.

    if it is 2ust a single user then we 2ust create a single row with the user data.

    Simple, as, that-

    CONCLUSION

    ow you have completed this codeigniter tutorialyou should now have a good

    understanding of how codeigniterworks. ou should know how to set%

  • 8/10/2019 Tutorial de CodeIgniter

    27/27

    up codeigniterincluding all the configuration, create models, views and

    controllers along with liraries and know how to load and use them successfully