CodeIgniter 1.7 - David Upton - E-Book

CodeIgniter 1.7 E-Book

David Upton

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

CodeIgniter (CI) is a powerful open-source PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. CodeIgniter is an MVC framework, similar in some ways to the Rails framework for Ruby, and is designed to enable, not overwhelm.
This book explains how to work with CodeIgniter in a clear logical way. It is not a detailed guide to the syntax of CodeIgniter, but makes an ideal complement to the existing online CodeIgniter user guide, helping you grasp the bigger picture and bringing together many ideas to get your application development started as smoothly as possible.
This book will start you from the basics, installing CodeIgniter, understanding its structure and the MVC pattern. You will also learn how to use some of the most important CodeIgniter libraries and helpers, upload it to a shared server, and take care of the most common problems. If you are new to CodeIgniter, this book will guide you from bottom to top. If you are an experienced developer or already know about CodeIgniter, here you will find ideas and code examples to compare to your own.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 354

Veröffentlichungsjahr: 2009

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

CodeIgniter 1.7
Credits
About the Authors
About the Reviewer
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code for the book
Errata
Piracy
Questions
1. Introduction to CodeIgniter
What can CodeIgniter do for you?
Save time
Make your site more robust
Keep your links up-to-date automatically
Preventing database SQL injection attacks and form prepping
Protect your site from XSS attacks
Make your code bolder
Send email attachments without hassles
Save bandwidth by zipping files that users need to download
What CI doesn't do
Yes, but…what is CodeIgniter? What are frameworks?
Comparing CI to other open source solutions (CakePHP and Joomla!)
What to choose
License
Summary
2. Setting up a CodeIgniter Site
Prerequisites
Installing CodeIgniter
Exploring the file structure
Does it work?—checking our CI installation
The configuration file
Autoloading libraries, helpers, and so on
Mod rewrite and apache .htaccess to achieve nice URL rewrites
Moving the application directory and the system directory—benefits
Summary
3. Navigating Your Site
MVC: Model-View-Controller
But how does all this work?
The welcome controller
Working with views
The default controller
CodeIgniter syntax rules
Controller
View
Types of files or classes on a CI site
Designing a better view
Designing a better controller
Getting parameters to a function
Passing data to a view
How CI classes pass information and control to each other
Calling views
Calling functions directly
Interacting with controllers
An example of a CI helper—the URL helper
A simple library example—creating a menu
Summary
4. Using CI to Simplify Databases
Configuration settings
Designing the database for our site
Active Record
Advantages of using the Active Record class
Saving time
Automatic functionality
Read queries
Displaying query results
Create and update queries
Delete queries
Mixing Active Record and "classic" styles
Dealing with complex queries
Summary
Chapter appendix: MySQL query to set up the website's database
5. Simplifying HTML Pages and Forms
Writing a view
Long and short PHP syntax and other CodeIgniter style guidelines
File format
PHP closing tag
Nesting views
Practical issues of site architecture
CI's form helper—entering data
Form helper advantage one: Clarity
Form helper advantage two: Automation
My display model
CI's form validation class: Checking data easily
Setting up validation
Setting up the controller
Setting up forms
Let's pack it all together
Summary
6. Simplifying Sessions and Security
Continuing with our practical site using CI
Moving around the site
Security/Sessions: Using another CI library class
Turning sessions into security
But what about logout?
Isn't there anything already built?
Security
Summary
7. CodeIgniter and Objects
Object-oriented programming
The CI super-object
Copying by reference
Adding your own code to the CI super-object
Problems with the CI super-object
Summary
8. Improving Our Application with Third-Party Code
Creating a helper
Creating a library
Sitemap
Explanation for My_Parser.php
Google charts plugin
Summary
9. Using CI to Communicate
Using the FTP class to test remote files
Machines talking to machines again: XML-RPC
Getting the XML-RPC server and client in touch with each other
Formatting XML-RPC exchanges
Debugging
Issues with XML-RPC
Talking to humans for a change—the email class
Twitter
Summary
10. How CI Helps to Provide Dynamic Information
The date helper—converting and localizing dates
The Calendar class
Working with text—the text helper
Going international—the Language class
Making HTML tables the easy way—the Table class
Caching pages
Summary
11. Using CI to Handle Files and Images
The file helper
The download helper
The file upload class and CI's image class
CI's image class
Easy file compression with CI's zip class
Summary
12. Moving Your Site to the WWW
Errors and error pages
So, should we update if a new version of CI comes out?
Steps/advice to follow when updating our CI version
Summary
13. CRUD—or Putting It All Together
Building our CRUD controller, model, and views
Upgrading our CRUD
Pagination class
Putting some order into our records
Summary
14. The Verdict on CI
Organizing the files of our site
Organizing the logic of our site
A model
A controller
A view
Centralized configuration
Code conventions
Database tools
Simpler and more powerful code
Adding security to our site
Making our site more scalable and our code more reusable
Documentation and community
Summarizing all that CI offers
Summary
15. Resources and Extensions
CI's user forums
Video tutorials
Available plugins and libraries
AJAX or JavaScript
Authentication
PDF generation
Comparisons: Which charting library to use?
HTML purifier
CRUD—the final frontier
Invoicing
Additional resources
Some books that could help
Resources for other programs: XAMPP Lite, MySQL, and PHP
Summary
A. Appendix
What we need to use the library
Adding products to the cart
Showing the cart to our clients
Summary
Index

CodeIgniter 1.7

David Upton

Jose Argudo

CodeIgniter 1.7

Copyright © 2009 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: November 2009

Production Reference: 1031109

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN: 978-1-847199-48-5

www.packtpub.com

Cover Image by Vinayak Chittar (<[email protected]>)

Credits

Authors

Jose Argudo Blanco

David Upton

Reviewer

Pascal Kriete

Acquisition Editor

Douglas Paterson

Development Editor

Swapna Verlekar

Technical Editor

Dhwani Devater

Indexer

Hemangini Bari

Editorial Team Leader

Abhijeet Deobhakta

Project Team Leader

Lata Basantani

Project Coordinator

Poorvi Nair

Proofreader

Chris Smith

Graphics

Nilesh R Mohite

Production Coordinator

Dolly Dasilva

Cover Work

Dolly Dasilva

About the Authors

Jose Argudo Blanco is a web developer from Valencia, Spain. After finishing his studies he started working for a web design company. After working for six years for that company and some others, he decided to work as a freelance.

Now, after some years have passed, he thinks it's the best decision he has ever taken—a decision that let him work with the tools he likes, such as CodeIgniter, Joomla!, CakePHP, JQuery, and other well-known open source technologies.

For the past few months he has also reviewed some books for Packt Publishing, such as Magento 1.3 Theme Design, Magento: Beginner's Guide, Joomla! 1.5 SEO, Symfony 1.3 Web Application Development, and Joomla! with Flash. The one yet to be published is Magento Development with PHP.

He has put a lot of effort into this book and hopes it's very useful for the readers.

To my girlfriend Silvia whose support helps me every day, to my brother, maybe some day we will work together, to my parents for being always there, and, of course, to Swapna, Poorvi, and all the Packt team, without their help, and Pascal's advices this book couldn't have been possible.

David Upton is a director of a specialized management consultancy company, based in London but working around the world. His clients include some of the world's largest companies. He is increasingly interested in web-enabling his work, and seeking to turn ideas into robust professional applications by the simplest and easiest route. So far he has written applications for two major companies in the UK. His other interests include simulation, on which he writes a weblog that takes up far too much of his time, and thinking.

About the Reviewer

Pascal Kriete is a developer from Germany. Although his background lies in engineering, after a short, unsuccessful stint in traditional server/client administration he found his way into freelance web development. Looking to streamline his development workflow—as freelancers want to do—he discovered CodeIgniter and began actively participating in the community. This involvement quickly spread to the ExpressionEngine forums and by the end of 2008 Pascal joined the EllisLab team as a Technical Support Specialist. He has since moved on to become a member of the development team, where he continues to polish code and gets to interact with an ever growing number of third-party developers.

Preface

CodeIgniter (CI) is a powerful open source PHP framework with a very small footprint, built for PHP programmers who need a simple and elegant toolkit to create full-featured web applications. CodeIgniter is an MVC framework, similar in some ways to the Rails framework for Ruby, and is designed to enable, not overwhelm. This book explains how to work with CodeIgniter in a clear logical way.

What this book covers

Chapter 1: Introduction to CodeIgniter, will introduce you to what frameworks are, and specifically we will talk about CI and how it can help in our day to day work. We will see what CI offers and what it doesn't.

Chapter 2: Setting up a CodeIgniter Site, will help you to prepare the basic configuration of your site, studying CI's structure and config files. At the end you will have a working CI installation.

Chapter 3: Navigating Your Site, will cover some important topics, like the MVC pattern and how CI handles this pattern, and we will make an example controller just to see how all this works.

Chapter 4: Using CI to Simplify Databases, helps you to start working with databases. This is a very important topic. CI will really help us at this point, so we are going to see in detail all the tools at our disposal, including Active Record.

Chapter 5: Simplifying HTML Pages and Forms, will help you with HTML and form helpers, which are some important tools you will find in CodeIgniter; we will see some examples about their usage and introduce form validation.

Chapter 6: Simplifying Sessions and Security, will cover some important security features of CI, which will help make your site more secure. As we will also talk about sessions we will build a simple login feature.

Chapter 7: CodeIgniter and Objects, introduces a bit on object-oriented programming and how CI makes use of it, including the use of the CI super object, and how we can modify and use it.

Chapter 8: Improving Our Application with Third-Party Code, will help you take some rest from the hard work you have done in the previous chapters. We will see some third-party code that we can easily add to our site, improving it, and adding interesting functionalities.

Chapter 9: Using CI to Communicate, explains how CI helps us in communication. Communication is an important part of every site. We will see the ftp class, email class, and XML-RPC class and, of course, the possibility to add more as we need!

Chapter 10: How CI Helps to Provide Dynamic Information, will show some more useful helpers and classes, this will include the date helper, text helper, and table and language classes. All of this will help in the development of our site, not only in reducing code, but in adding powerful features to our working toolbox.

Chapter 11: Using CI to Handle Files and Images, will be about files, uploading, downloading, and compressing them, of course, all with CI classes! As always those classes will make our life easier. Image treatment also has some space in the chapter as CI has some nice features to crop, reduce, watermark, and so on.

Chapter 12: Moving Your Site to the WWW, will finally show you how to upload your site to a shared host or similar. Here we will see in detail how to do that, and also what kind of error we can expect to encounter.

Chapter 13: CRUD—or Putting It All Together, will be a chapter of "putting it all together", where we'll take time to recap and emphasize the most important topics covered to the moment. Insert, edit, and remove records from the database are some topics we will see here, but also ordering and pagination of results.

Chapter 14: The Verdict on CI, will summarize the key points of CI, not to forget anything, as every little thing CI offers will be of great help.

Chapter 15: Resources and Extensions, will give a list of resources and third-party code—we don't want to reinvent the wheel! We will take a look at some useful extensions such as authentication, PDF generation, invoicing, and much more.

The Appendix will introduce a new and interesting CI feature, the cart class; building a store has never been easier!

What you need for this book

Only basic PHP and HTML knowledge is needed to understand this book. All the rest is explained here from top to bottom. You won't get lost!

Who this book is for

This book is not only for PHP developers who want to be more productive at work, but also for those who are new to web programming and are searching for a useful tool that helps in their work. If you are tired of writing the same code again and again, this book is for you. If you want to create more robust and easier-to-maintain PHP sites, again this book is for you. But this book is really for you if you want to enjoy PHP programming with a framework that really helps you.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply drop an email to <[email protected]>, and mention the book title in the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code for the book

Visit http://www.packtpub.com/files/code/9485_Code.zip to directly download the example code.

Note

The downloadable files contain instructions on how to use them.

Errata

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

What CI doesn't do

There are some things that CI doesn't do. CI was intended to be a small and lightweight framework. The zipped download for version 1.7.2 is only 2.1 MB and is downloaded in seconds, whereas the Zend framework is 10 MB. It won't answer all the problems you will have. But it does:

Make it easy and quick to program in PHPStructure your site and help you through the architectural decisions

As a result of being lightweight, it does not have as many features as some of its rivals. Other frameworks such as Rails, CakePHP, or Symfony have scaffolding and generators. These tools automatically write certain basic scripts for you.

Once you have set up a database, Rails creates out-of-the-box web pages to do basic Create, Read, Update, and Delete (CRUD) operations on the database tables. In addition, Rails allows you to write generators—pieces of code that automatically write other basic scripts. The Rails community has created quite a lot of these, so you can automatically generate scripts that do all sorts of clever things.

CI concentrates on making basic things easy. Some of the things it handles are:

Session management and cookies (see Chapter 6)Database access and queries (see Chapter 4)Building HTML stuff, like pages and forms, and validating form entries (see Chapter 5)Communicating on the Internet, using FTP (Chapter 9)

Sounds familiar? All of these are basic processes, which you will have to go through if you're building a dynamic website. CI makes these processes easier, and makes your code more likely to work. Join this outstanding community; it will help you in case you need it (at the CodeIgniter forums). You can even share code at the Wiki (http://codeigniter.com/wiki/), and you will find why CI is so popular.

Yes, but…what is CodeIgniter? What are frameworks?

Shortly after programming was invented, it was noticed that it involved many repetitive operations. And maybe shortly after that, Ada Lovelace—spanner in hand adjusting Babbage's differential engine—or Alan Turing at Bletchley Park decided to modularize code. So, you only had to write certain chunks once, and could then reuse them. PHP programmers are used to writing separate chunks of code in functions, and then storing those functions in include files.

At one level, a framework is just that—lot of chunks of code stored in separate files, which simplify the coding of repetitive operations. In the previous examples, connecting to the database or building HTML form elements are abstracted and simplified for you. You call a function in the framework, which is easy to handle than the original code.

It goes beyond that. Writing code involves continuous choices between the many ways of tackling the same problem. Most frameworks impose a set of choices on you. They've started to handle the problem one way, so you have to go that way as well. If they are sensible choices, it makes your life much simpler. If not, it's like trying to write a sales brochure using Excel, or showing cash flow projections using Word. Both can probably be done, but neither is the best use of your time.

Sensible design decisions make sure that the things you need are accessible, but prevent them from spilling over into each other. A good framework makes these decisions for you—starting off with a sensible foundation for your program and guiding you through the next steps.

A framework will also improve team programming. As every developer has to adhere to the framework syntax and structure, it is an important part of software maintainability. The code you write today needs to be readable by other people in future. Imagine you arrive to a new workplace and then you inherit a couple of projects. In a perfect world those projects would be well commented, but reality usually hits... Wouldn't it be nice to have a central resource of documentation to get started with those projects?

Most frameworks will offer good documentation. CI isn't an exception; everything is well documented—functions, structures, conventions. You won't have to imagine what a certain function does, you will know it. A very good starting point, don't you think?

Nowadays there are lot of frameworks out there, not only PHP frameworks but Ruby frameworks, Python frameworks, and so on. For PHP programmers there are hundreds of options (well, may not be hundreds, but if we do search for PHP frameworks the results will be overwhelming). Of all these options there are some that are more popular; CI is among them, with others such as CakePHP, Zend Framework, Symfony, and more.

As you are reading this book, you are interested in PHP frameworks, especially CodeIgniter, so we will keep to it.

If you take a look at http://phpframeworks.com/ and http://www.phpframeworks.com/top-10-php-frameworks/, you will see how well CodeIgniter is doing. CI is very popular as a PHP framework; with this book you will know, why. Also if you look at some forums and blogs you'll notice that postings get very heated about which framework is the best. The truth seems to be that each has its strengths, and none is without its own weaknesses. In time you will learn to decide which framework to use in which project. It is recommended that you should think about which tool to use, before starting your projects. Choose the one that will help you to end with a well done project, in good time, and with the best possible scalability. Most of the times CI helps achieve this.

Comparing CI to other open source solutions (CakePHP and Joomla!)

For one reason or another one should compare these three most of the time and, of course, use one of them. There are other solutions out there, as we have commented before, "few" is not the word to describe PHP frameworks.

Though you would like to have Zend Framework and Symfony in your toolbox, for now, let's use these three for comparison. For example, when Jose heard about frameworks it was all about Ruby on Rails. Before that he used to write his own code for every project. Though Ruby on Rails is a very good framework, for him—a PHP programmer at heart—that was not the solution.

Searching for a PHP framework that was similar to Ruby on Rails, but PHP made, CakePHP was one option. It was quite similar in concept to Ruby on Rails, it also had the same convention-driven architecture that you need to learn before using it. It will pay-back with lots of functionality, automation, and more. But keep in mind that the learning curve is steeper than CodeIgniter's.

Using CakePHP requires you to adhere to some strict conventions (those can be changed but the out-of-the-box software comes with them). Most of the time they are naming conventions, but there are database conventions also.

After some time, because of curiosity, in spite of incredible lack of learning time (some nearby shouting boss also helped), continuing research of PHP frameworks found CodeIgniter. The most convincing thing was the documentation (CakePHP wasn't as well documented as it is today).

CI has less conventions, and minimal configuration, also you can forget about most of them and work as you have always done. You don't want to use models, and you don't have to (though it is recommended). That said, one of the strengths of CI is just that—download it and start programming.

Joomla! is not exactly a framework, it helps you build websites faster. Also in the latest versions it has turned into the MVC (Model-View-Controller) pattern. The good part of Joomla! is that it is a CMS (Content Management System), but I think it is also its bad part, as sometimes you just don't need so much as Joomla! has to offer. Of course you can develop your own solution over Joomla!, but then what's the point of using Joomla!, and not using what it has to offer?

CI, usually, is the most well-balanced of the three, but let's see how we can choose one of them.

What to choose

With all those options out there, why should you go with CI? The answer—it's not that easy and involves, in most cases, personal preference. There will be projects that will be better suited to one of the other two options. Let's see some examples that will guide us.

When to choose Joomla!

If we need a CMS (it may sound redundant, but...).If there is already a component, module, or some other functionality that we need, then there is something built that can help us carry out the project in no time.If the client asks you to use it. Joomla! is a well known software, andsometimes your client can just ask you to use it.

When to choose CakePHP

If there are lot of relations between database tables. Cake's Active Record capabilities are slightly more powerful than CI's. If you need to build some admin zone quickly. Cake's bake script can read your database and build some CRUD (Create, Read, Update, Delete) pages for your tables.

When to choose CodeIgniter

If the project doesn't have or doesn't need a very rigid structure. Also CI is good for working with legacy code.If you need to start programming right away, without having to learn a lot of conventions.If you need some software that helps you, with the confidence that it will help you in the way you really need, and learn the way something needs to be done.If you know PHP, you can use CI.The client needs some solution built specifically for him/her, and not an adapted solution (that would be in case of some Joomla! components/modules).

Most of the time we will be using CI because it is very flexible. If you like programming CI will help you in doing it. It will seem as if CI isn't even there. You realize it only when you look at the time you are gaining and the better structure of your project.

If you are new to frameworks it is recommended that you get CI, maybe later you use another one (probably both of them), but CI will always have a place in your heart.

Note

Packt Publishing has books on some other frameworks and Joomla!. It is recommended to read them, it will give you a broader view of things.

For books on Joomla visit http://www.packtpub.com/joomla-version-1-5/book.

For books on CakePHP visit http://www.packtpub.com/cakephp-application-development/book.

License

If you are building a commercial application, the license terms for any software you are using become critical. If you are raising venture capital, expect the VC's lawyers to go over them in detail. With CI this is not a problem. It has a very generous license that is downloaded with your files.

Unlike some commercial software, CI's license even fits on one screen. Here it is, in the following screenshot:

Summary

If you already know some PHP and are designing intelligent websites, the CodeIgniter framework is all about making your life easier. It helps you to:

Save timeMake your site more robustAchieve more sophisticated codingIt makes coding fun again, rather than a chore

There are quite a lot of frameworks and all of them offer chunks of pre-written code that make the repetitive or complex processes of coding easier and not just for the PHP language. They impose a helpful structure on your site's development.

This book does not make any comparisons between frameworks. CI works for most, and we will see, how and why. It will be useful for you too, and you will be able to save much time and, as a result, enjoy the coding process more.

This book takes you through some of the framework's main features, and tries to explain some of what goes on "under the hood". We've used a real-world example for the code illustrations in this book to show that CI is a serious tool that can be quickly and easily used in a demanding environment.

Enjoy!

Chapter 2. Setting up a CodeIgniter Site

Setting up the CI package on your web server or a local machine is easy. This chapter explains, what happens when you install the site and which files will be created. Let's look at:

What software you require for your site's developmentInstalling the CI files—a simple download and unzip operationThe basic configuration of CI—which folders are there and how they are organizedThe initial controller and view that CI installsSome basic modifications to show how these work

Prerequisites