CodeIgniter 사용자 가이드 Version 2.1.0-번역 한국 CI 사용자 그룹


CodeIgniter

코드 이그나이터의 세계에 오신것을 환영합니다.

코드이그나이터(이하 CI)는 PHP를 이용하여 웹사이트를 구축하고자 하는 사람들을 위한 개발 프레임 워크 입니다. CI 는 날코딩 하는 분들을 위해 풍부한 라이브러리,쉬운 인터페이스 및 쉬운로직을 제공함으로써 개발속도를 무쟈게 높혀드릴것입니다. CI는 님들이 최소한의 코딩만 하도록 하여 프로젝트에 집중할수 있도록 해드릴거예요.

 

코드이그나이터는 누구를 위한것인가?

코드이그나이터는 바로 이런 여러분 모두의 것입니다:

Server Requirements : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


서버 요구사항 Server Requirements

CodeIgniter License Agreement : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


CodeIgniter License Agreement

Copyright (c) 2008 - 2011, EllisLab, Inc.
All rights reserved.

This license is a legal agreement between you and EllisLab Inc. for the use of CodeIgniter Software (the "Software"). By obtaining the Software you agree to comply with the terms and conditions of this license.

Permitted Use

You are permitted to use, copy, modify, and distribute the Software and its documentation, with or without modification, for any purpose, provided that the following conditions are met:

  1. A copy of this license agreement must be included with the distribution.
  2. Redistributions of source code must retain the above copyright notice in all source code files.
  3. Redistributions in binary form must reproduce the above copyright notice in the documentation and/or other materials provided with the distribution.
  4. Any files that have been modified must carry notices stating the nature of the change and the names of those who changed them.
  5. Products derived from the Software must include an acknowledgment that they are derived from CodeIgniter in their documentation and/or other materials provided with the distribution.
  6. Products derived from the Software may not be called "CodeIgniter", nor may "CodeIgniter" appear in their name, without prior written permission from EllisLab, Inc.

Indemnity

You agree to indemnify and hold harmless the authors of the Software and any contributors for any direct, indirect, incidental, or consequential third-party claims, actions or suits, as well as any related expenses, liabilities, damages, settlements or fees arising from your use or misuse of the Software, or a violation of any terms of this license.

Disclaimer of Warranty

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF QUALITY, PERFORMANCE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

Limitations of Liability

YOU ASSUME ALL RISK ASSOCIATED WITH THE INSTALLATION AND USE OF THE SOFTWARE. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS OF THE SOFTWARE BE LIABLE FOR CLAIMS, DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE. LICENSE HOLDERS ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USE AND ASSUME ALL RISKS ASSOCIATED WITH ITS USE, INCLUDING BUT NOT LIMITED TO THE RISKS OF PROGRAM ERRORS, DAMAGE TO EQUIPMENT, LOSS OF DATA OR SOFTWARE PROGRAMS, OR UNAVAILABILITY OR INTERRUPTION OF OPERATIONS.

Credits : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


명예 Credits

CodeIgniter 는 Rick Ellis (Ellislab, Inc. 의 CEO )에 의해 최초로 개발되었습니다.본 프레임워크는 ExpressionEngine의 기반코드에서 많은것을 빌려와 여러가지 클래스 라이브러리,헬퍼,하위시스템등을 구성하였으며, 실재상황에서 최상의 성능을 내기위해 만들어 졌습니다.

현재는 개발 및 유지보수를 ExpressionEngine 개발팀이 맡고 있습니다.

Ruby on Rails 의 걸출한 업적이 우리에게 PHP 프레임워크를 만들도록 영감을 주었으며, 웹 커뮤니티에게 프레임워크가 일반적이라는 인식을 가질 수 있도록 해 주었습니다.

Upgrading from 2.0.2 to 2.0.3 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 2.0.2 to 2.0.3

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your main index.php file

If you are running a stock index.php file simply replace your version with the new one.

If your index.php file has internal modifications, please add your modifications to the new file and use it.

Step 3: Replace config/user_agents.php

This config file has been updated to contain more user agent types, please copy it to application/config/user_agents.php.

Step 4: Change references of the EXT constant to ".php"

Note: The EXT Constant has been marked as deprecated, but has not been removed from the application. You are encouraged to make the changes sooner rather than later.

Step 5: Remove APPPATH.'third_party' from autoload.php

Open application/autoload.php, and look for the following:

$autoload['packages'] = array(APPPATH.'third_party');

If you have not chosen to load any additional packages, that line can be changed to:

$autoload['packages'] = array();

Which should provide for nominal performance gains if not autoloading packages.

Update Sessions Database Tables

If you are using database sessions with the CI Session Library, please update your ci_sessions database table as follows:

CREATE INDEX last_activity_idx ON ci_sessions(last_activity); ALTER TABLE ci_sessions MODIFY user_agent VARCHAR(120);
Upgrading from 1.5.4 to 1.6.0 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.5.4 to 1.6.0

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Add time_to_update to your config.php

Add the following to application/config/config.php with the other session configuration options

$config['sess_time_to_update'] = 300;

Step 3: Add $autoload['model']

Add the following to application/config/autoload.php

/*
| -------------------------------------------------------------------
| Auto-load Model files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('my_model');
|
*/

$autoload['model'] = array();

Step 4: Add to your database.php

Make the following changes to your application/config/database.php file:

Add the following variable above the database configuration options, with $active_group

$active_record = TRUE;

Remove the following from your database configuration options

$db['default']['active_r'] = TRUE;

Add the following to your database configuration options

$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";

Step 5: Update your user guide

Please also replace your local copy of the user guide with the new version.

CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.3.1 to 1.3.2

Note: The instructions on this page assume you are running version 1.3.1. If you have not upgraded to that version please do so first.

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace the following directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your user guide

Please also replace your local copy of the user guide with the new version.

CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.4.1 to 1.5.0

Note: The instructions on this page assume you are running version 1.4.1. If you have not upgraded to that version please do so first.

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your database.php file

Open your application/config/database.php file and add these new items:

$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';

Step 3: Update your config.php file

Open your application/config/config.php file and ADD these new items:

/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries.  For more information please see the user guide:
|
| http://codeigniter-kr.org/user_guide_2.1.0/general/core_classes.html
| http://codeigniter-kr.org/user_guide_2.1.0/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';

/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files.  Options are TRUE or FALSE (boolean)
|
*/
$config['rewrite_short_tags'] = FALSE;

In that same file REMOVE this item:

/*
|--------------------------------------------------------------------------
| Enable/Disable Error Logging
|--------------------------------------------------------------------------
|
| If you would like errors or debug messages logged set this variable to
| TRUE (boolean).  Note: You must set the file permissions on the "logs" folder
| such that it is writable.
|
*/
$config['log_errors'] = FALSE;

Error logging is now disabled simply by setting the threshold to zero.

Step 4: Update your main index.php file

If you are running a stock index.php file simply replace your version with the new one.

If your index.php file has internal modifications, please add your modifications to the new file and use it.

Step 5: Update your user guide

Please also replace your local copy of the user guide with the new version.

Upgrading from 1.7.1 to 1.7.2 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.7.1 to 1.7.2

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Remove header() from 404 error template

If you are using header() in your 404 error template, such as the case with the default error_404.php template shown below, remove that line of code.

<?php header("HTTP/1.1 404 Not Found"); ?>

404 status headers are now properly handled in the show_404() method itself.

Step 3: Confirm your system_path

In your updated index.php file, confirm that the $system_path variable is set to your application's system folder.

Step 4: Update your user guide

Please replace your local copy of the user guide with the new version, including the image files.

Installation Instructions : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


설치 절차 Installation Instructions

CodeIgniter 설치는 다음 4단계를 거칩니다:

  1. 다운받은 파일의 압축을 푼다.
  2. CodeIgniter 를 서버에 업로드한다. 일반적으로 index.php 을 홈페이지 루트에 오도록 해야 한다.
  3. application/config/config.php 파일을 열어 기반url(base URL)을 세팅한다. 암호화나 세션을 사용하려면 암호키(encryption key)를 설정한다.
  4. 데이터베이스를 사용한다면 application/config/database.php 파일을 열어서 데이터베이스 정보를 세팅한다.

system 폴더의 이름을 변경하여 보안을 강화할수 있습니다. 만약 변경한다면 반드시 메인 index.php 파일을 열어 맨위에 있는 $system_folder 변수와 $application_folder 변수의 값을 새 폴더 이름을 바꿔야합니다.

보안으로 가장 좋은 방법은, systemapplication 폴더를 브라우저에서 직접 액세스할 수없는 위치에 옮기는 것입니다. 기본적으로 각 폴더에 .htaccess 파일이 존재니다만, 서버설정에 따라서 동작하지않을 수 도 있으므로, 브라우저에서 접근 불가능한 경로에두는것이 가장 좋습니다.

추가 대책으로 프로덕션 환경에서 PHP 오류보고와 다른 개발 기능을 비활성화했습니다. 비활성화는 ENVIRONMENT 설정을 통해 이루어졌으며 자세한 내용은 보안 클래스 를 확인하십시오.

 

끝 !

CodeIgniter를 처음 시작하신다면 시작하기 부분을 먼저 읽어보시길 권합니다.

그럼 지금부터 신나는 프로그램을 즐겨 주세요!

Upgrading from 1.6.3 to 1.7.0 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.6.3 to 1.7.0

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your Session Table

If you are using the Session class in your application, AND if you are storing session data to a database, you must add a new column named user_data to your session table. Here is an example of what this column might look like for MySQL:

user_data text NOT NULL

To add this column you will run a query similar to this:

ALTER TABLE `ci_sessions` ADD `user_data` text NOT NULL

You'll find more information regarding the new Session functionality in the Session class page.

Step 3: Update your Validation Syntax

This is an optional, but recommended step, for people currently using the Validation class. CI 1.7 introduces a new Form Validation class, which deprecates the old Validation library. We have left the old one in place so that existing applications that use it will not break, but you are encouraged to migrate to the new version as soon as possible. Please read the user guide carefully as the new library works a little differently, and has several new features.

Step 4: Update your user guide

Please replace your local copy of the user guide with the new version, including the image files.

Upgrading from 2.0.0 to 2.0.1 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 2.0.0 to 2.0.1

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Replace config/mimes.php

This config file has been updated to contain more mime types, please copy it to application/config/mimes.php.

Step 3: Check for forms posting to default controller

The default behavior for form_open() when called with no parameters used to be to post to the default controller, but it will now just leave an empty action="" meaning the form will submit to the current URL. If submitting to the default controller was the expected behavior it will need to be changed from:

echo form_open(); //<form action="" method="post" accept-charset="utf-8">

to use either a / or base_url():

echo form_open('/'); //<form action="http://example.com/index.php/" method="post" accept-charset="utf-8">
echo form_open(base_url()); //<form action="http://example.com/" method="post" accept-charset="utf-8">
Upgrading from 1.6.2 to 1.6.3 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.6.2 to 1.6.3

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your user guide

Please also replace your local copy of the user guide with the new version.

Downloading CodeIgniter : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


CodeIgniter 다운로드

Git Server

Git는 분선 버전관리 시스템입니다.

GitHub에서 공개 GIT로 접근이 가능합니다. 모든 GIT의 코드가 정상동작한다고 보증할 수 없습니다..

2.0.3 부터는 GitHub 에서 안정버전 태그를 찾으실 수 있습니다.

CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.2 to 1.3

Note: The instructions on this page assume you are running version 1.2. If you have not upgraded to that version please do so first.

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace the following directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your error files

Version 1.3 contains two new error templates located in application/errors, and for naming consistency the other error templates have been renamed.

If you have not customized any of the error templates simply replace this folder:

If you have customized your error templates, rename them as follows:

Step 3: Update your index.php file

Please open your main index.php file (located at your root). At the very bottom of the file, change this:

require_once BASEPATH.'libraries/Front_controller'.EXT;

To this:

require_once BASEPATH.'codeigniter/CodeIgniter'.EXT;

Step 4: Update your config.php file

Open your application/config/config.php file and add these new items:

/*
|------------------------------------------------
| URL suffix
|------------------------------------------------
|
| This option allows you to add a suffix to all URLs.
| For example, if a URL is this:
|
| example.com/index.php/products/view/shoes
|
| You can optionally add a suffix, like ".html",
| making the page appear to be of a certain type:
|
| example.com/index.php/products/view/shoes.html
|
*/
$config['url_suffix'] = "";


/*
|------------------------------------------------
| Enable Query Strings
|------------------------------------------------
|
| By default CodeIgniter uses search-engine and
| human-friendly segment based URLs:
|
| example.com/who/what/where/
|
| You can optionally enable standard query string
| based URLs:
|
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The two other items let you set the query string "words"
| that will invoke your controllers and functions:
| example.com/index.php?c=controller&m=function
|
*/
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';

Step 5: Update your database.php file

Open your application/config/database.php file and add these new items:

$db['default']['dbprefix'] = "";
$db['default']['active_r'] = TRUE;

Step 6: Update your user guide

Please also replace your local copy of the user guide with the new version.

CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.5.2 to 1.5.3

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your user guide

Please also replace your local copy of the user guide with the new version.

CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.4.0 to 1.4.1

Note: The instructions on this page assume you are running version 1.4.0. If you have not upgraded to that version please do so first.

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace the following directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your config.php file

Open your application/config/config.php file and add this new item:


/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads.  When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| VERY IMPORTANT:  If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts.  For
| compression to work, nothing can be sent before the output buffer is called
| by the output class.  Do not "echo" any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;

Step 3: Rename an Autoload Item

Open the following file: application/config/autoload.php

Find this array item:

$autoload['core'] = array();

And rename it to this:

$autoload['libraries'] = array();

This change was made to improve clarity since some users were not sure that their own libraries could be auto-loaded.

Step 4: Update your user guide

Please also replace your local copy of the user guide with the new version.

Upgrading from 2.0.1 to 2.0.2 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 2.0.1 to 2.0.2

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Remove loading calls for the Security Library

Security has been moved to the core and is now always loaded automatically. Make sure you remove any loading calls as they will result in PHP errors.

Step 3: Move MY_Security

If you are overriding or extending the Security library, you will need to move it to application/core.

csrf_token_name and csrf_hash have changed to protected class properties. Please use security->get_csrf_hash() and security->get_csrf_token_name() to access those values.

Upgrading From a Previous Version : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


이전 버전에서 업그레이드 하기

버전에 알맞은 업그레이드 방법을 읽어보세용.

CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.3 to 1.3.1

Note: The instructions on this page assume you are running version 1.3. If you have not upgraded to that version please do so first.

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace the following directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your user guide

Please also replace your local copy of the user guide with the new version.

Upgrading from 1.7.0 to 1.7.1 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.7.0 to 1.7.1

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your user guide

Please replace your local copy of the user guide with the new version, including the image files.

Upgrading from 1.7.2 to 2.0.0 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.7.2 to 2.0.0

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace all files and directories in your "system" folder except your application folder.

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Adjust get_dir_file_info() where necessary

Version 2.0.0 brings a non-backwards compatible change to get_dir_file_info() in the File Helper. Non-backwards compatible changes are extremely rare in CodeIgniter, but this one we feel was warranted due to how easy it was to create serious server performance issues. If you need recursiveness where you are using this helper function, change such instances, setting the second parameter, $top_level_only to FALSE:

get_dir_file_info('/path/to/directory', FALSE);

Step 3: Convert your Plugins to Helpers

2.0.0 gets rid of the "Plugin" system as their functionality was identical to Helpers, but non-extensible. You will need to rename your plugin files from filename_pi.php to filename_helper.php, move them to your helpers folder, and change all instances of: $this->load->plugin('foo'); to $this->load->helper('foo');

Step 4: Update stored encrypted data

Note: If your application does not use the Encryption library, does not store Encrypted data permanently, or is on an environment that does not support Mcrypt, you may skip this step.

The Encryption library has had a number of improvements, some for encryption strength and some for performance, that has an unavoidable consequence of making it no longer possible to decode encrypted data produced by the original version of this library. To help with the transition, a new method has been added, encode_from_legacy() that will decode the data with the original algorithm and return a re-encoded string using the improved methods. This will enable you to easily replace stale encrypted data with fresh in your applications, either on the fly or en masse.

Please read how to use this method in the Encryption library documentation.

Step 5: Remove loading calls for the compatibility helper.

The compatibility helper has been removed from the CodeIgniter core. All methods in it should be natively available in supported PHP versions.

Step 6: Update Class extension

All core classes are now prefixed with CI_. Update Models and Controllers to extend CI_Model and CI_Controller, respectively.

Step 7: Update Parent Constructor calls

All native CodeIgniter classes now use the PHP 5 __construct() convention. Please update extended libraries to call parent::__construct().

Step 8: Update your user guide

Please replace your local copy of the user guide with the new version, including the image files.

Upgrading from 2.0.3 to 2.1.0 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


2.0.3 에서 2.1.0으로 업그레이드

업그레이드 하기전에 사이트를 내려주세요.

스텝 1: CodeIgniter 파일 업그레이드

Replace all files and directories in your "system" 폴더의 모든 파일과 디렉토리를 2.1.0으로 바꾸어 주세요.그리고 index.php파일도 바꿔주시구요.index.php 내용중 바뀐것이 있다면, 새로운 index.php도 그대로 바꾸어 주셔야합니다..

주의: 기존 버전에서 커스터마이징 하신것이 있으면, 먼저 백업해 두시구요.

스텝 2: config/user_agents.php 파일 바꾸기

이 파일에 user agent 타입이 추가되었습니다.application/config/user_agents.php에 복사해주세요.

Upgrading from 1.6.0 to 1.6.1 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.6.0 to 1.6.1

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your user guide

Please also replace your local copy of the user guide with the new version.

CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.5.0 to 1.5.2

Note: The instructions on this page assume you are running version 1.5.0 or 1.5.1. If you have not upgraded to that version please do so first.

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your user guide

Please also replace your local copy of the user guide with the new version.

CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.3.3 to 1.4.0

Note: The instructions on this page assume you are running version 1.3.3. If you have not upgraded to that version please do so first.

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace the following directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your config.php file

Open your application/config/config.php file and add these new items:


/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the "hooks" feature you must enable it by
| setting this variable to TRUE (boolean).  See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;


/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible.  By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_-';

Step 3: Update your user guide

Please also replace your local copy of the user guide with the new version.

Upgrading from 1.6.1 to 1.6.2 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.6.1 to 1.6.2

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Encryption Key

If you are using sessions, open up application/config/config.php and verify you've set an encryption key.

Step 3: Constants File

Copy /application/config/constants.php to your installation, and modify if necessary.

Step 4: Mimes File

Replace /application/config/mimes.php with the dowloaded version. If you've added custom mime types, you'll need to re-add them.

Step 5: Update your user guide

Please also replace your local copy of the user guide with the new version.

Upgrading from 1.5.3 to 1.5.4 : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.5.3 to 1.5.4

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace these files and directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Add charset to your config.php

Add the following to application/config/config.php

/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
*/
$config['charset'] = "UTF-8";

Step 3: Autoloading language files

If you want to autoload any language files, add this line to application/config/autoload.php

$autoload['language'] = array();

Step 4: Update your user guide

Please also replace your local copy of the user guide with the new version.

Troubleshooting : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


문제해결 Troubleshooting

어떤 URL 을 집어넣어도 디폴트 페이지만 나온다면 서버에서 PATH_INFO 변수를 지원하지않은 경우일 가능성이 큽니다. PATH_INFO 변수는 검색엔진에 색인되기 좋은 URLs을 만드는데 필요합니다. 이를 해결하기 위해서는 먼저 application/config/config.php 파일을 열어 URI Protocol 정보를 살펴보세요. 대체할만한 여러세팅을 시도해보시길 권장드립니다. 그래도 정상동작하지않는다면 CodeIgniter 가 ? 를 사용하도록 설정해야합니다.

application/config/config.php 을 여신다음 아래의 부분을

$config['index_page'] = "index.php";

아래와 같이 변경합니다:

$config['index_page'] = "index.php?";
CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading From Beta 1.0 to Final 1.2

To upgrade to Version 1.2 please replace the following directories with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Please also replace your local copy of the user guide with the new version.

CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading From Beta 1.0 to Beta 1.1

To upgrade to Beta 1.1 please perform the following steps:

Step 1: Replace your index file

Replace your main index.php file with the new index.php file. Note: If you have renamed your "system" folder you will need to edit this info in the new file.

Step 2: Relocate your config folder

This version of CodeIgniter now permits multiple sets of "applications" to all share a common set of backend files. In order to enable each application to have its own configuration values, the config directory must now reside inside of your application folder, so please move it there.

Step 3: Replace directories

Replace the following directories with the new versions:

Step 4: Add the calendar language file

There is a new language file corresponding to the new calendaring class which must be added to your language folder. Add the following item to your version: language/english/calendar_lang.php

Step 5: Edit your config file

The original application/config/config.php file has a typo in it Open the file and look for the items related to cookies:

$conf['cookie_prefix'] = "";
$conf['cookie_domain'] = "";
$conf['cookie_path'] = "/";

Change the array name from $conf to $config, like this:

$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";

Lastly, add the following new item to the config file (and edit the option if needed):


/*
|------------------------------------------------
| URI PROTOCOL
|------------------------------------------------
|
| This item determines which server global
| should be used to retrieve the URI string. The
| default setting of "auto" works for most servers.
| If your links do not seem to work, try one of
| the other delicious flavors:
|
| 'auto' Default - auto detects
| 'path_info' Uses the PATH_INFO
| 'query_string' Uses the QUERY_STRING
*/

$config['uri_protocol'] = "auto";
CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


Upgrading from 1.3.2 to 1.3.3

Note: The instructions on this page assume you are running version 1.3.2. If you have not upgraded to that version please do so first.

Before performing an update you should take your site offline by replacing the index.php file with a static one.

Step 1: Update your CodeIgniter files

Replace the following directories in your "system" folder with the new versions:

Note: If you have any custom developed files in these folders please make copies of them first.

Step 2: Update your Models

If you are NOT using CodeIgniter's Models feature disregard this step.

As of version 1.3.3, CodeIgniter does not connect automatically to your database when a model is loaded. This allows you greater flexibility in determining which databases you would like used with your models. If your application is not connecting to your database prior to a model being loaded you will have to update your code. There are several options for connecting, as described here.

Step 3: Update your user guide

Please also replace your local copy of the user guide with the new version.

Application Flow Chart : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


CI 동작 개념도 Application Flow Chart

아래 그림은 CI 사용시 데이터의 흐름을 보여줍니다(화살표를 따라가면서 설명을 읽어보세요):

CodeIgniter application flow
  1. The index.php 는 프론트콘트롤러(front controller)로 동작하여 CI가 동작하기 위한 기반리소스들을 초기화 합니다.
  2. 라우터모듈(Routing)은 http 요청을 분석하여 어떤 동작을 해야할지를 결정합니다.
  3. 캐쉬파일이 있다면 그파일을 바로 브라우저로 보내고 일반적인 동작절차는 무시합니다.
  4. 보안모듈(Security)은 프로그램 컨트롤러가 로딩 되기전에 HTTP 요청및 어떤 사용자 전송데이터든지 모두 필터링합니다.
  5. 컨트롤러(Application controller)는 사용자 요청을 처리하기 위해 모델을 로드하고,코어라이브러리,헬퍼 및 필요한 다른 리소스들을 로드 합니다.
  6. 최종적으로 뷰모듈(View)이 렌더링되어 브라우저로 전송됩니다. 캐싱이 활성화 되어이다면 먼저 캐쉬(Cashing)하여 다음번 요청에 사용할 수 있도록 합니다.
Model-View-Controller : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


모델 뷰 컨트롤러 Model-View-Controller

CodeIgniter는 모델-뷰-컨트롤러(MVC) 개발 패턴에 기반합니다. MVC는 프로그램의 로직을 프리젠테이션(표현부분)로부터 분리하는 소프트웨어 접근 방법론 입니다. 실재로, 이것은 여러분의 웹페이지에 최소한의 스크립트만 들어가도록 해 줍니다.

CodeIgniter는 모델이 필요없도록 MVC를 매우 느슨하게 접근하였습니다. 만약 모델을 분리할 필요가 없거나, 모델을 따로 분리하는것이 쓸데없이 복잡도를 증가시킨다면, 컨트롤러와 뷰 파일만으로 프로그램을 만드실 수 있습니다. CodeIgniter는 여러분이 이미 가지고 있는 스크립트를 연동해서 사용하거나, 여러분의 기호에 맞게 시스템 코어라이브러리를 개발하여 쓸수도 있도록 했습니다.

Design and Architectural Goals : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


설계의 목적 Design and Architectural Goals

CodeIgniter 는극한의 성능, 적용성, 최소성 ,유연성,가벼움 을 목적으로 설계되었습니다.

이 목적을 만족시키기위해서 벤치마킹,리펙토링,단순화하기 등을 개발의 전 과정에서 수행하였습니다.

그리고, 이 목적에 맞지않는것은 단호히 제거하였습니다.

 

기술적,설계적 관점에서 CodeIgniter는 다음의 목표를 따릅니다.

 

위 목표로 인하여 CodeIgniter 는 작은 패키지 이면서도 단순성,유연성,고가용성을 달성하기위해 노력하고있습니다.

CodeIgniter Overview : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


CodeIgniter 살펴보기

아래 페이지에서 CodeIgniter에 녹아있는 컨셉을 확인하세요:

CodeIgniter at a Glance : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


CodeIgniter 한눈에 둘러보기 CodeIgniter at a Glance

CodeIgniter 는 프레임워크 입니다

CodeIgniter 는 PHP를 이용하여 웹사이트를 개발하고자하는 사람들을 위한 도구모음 입니다. 날코딩을 하고계셨다면 님하의 개발속도를 훨씬 향상시켜줄 것입니다. 이를 위해 CI는 일반적 작업에 사용되는 풍부한 라이브러리를 제공합니다. 게다가 라이브러리사용은 논리적이며 쉬운 인터페이스를 제공합니다.CI는 최소코딩만 필요하게 하므로써 님하의 생산성을 향상시켜주는데 촛점이 맞춰져 있습니다.

CodeIgniter 는 무료입니다

CodeIgniter 는 Apache/BSD 스타일의 오픈소스 라이센스를 채택하고있습니다. 더 자세한 정보는 라이센스 페이지를 참고하세요 .

CodeIgniter 는 가볍습니다

엄청 가볍습니다. 코어시스템은 겨우 몇개의 작은 라이브러리만 사용합니다. 이점은 다른 수많은 프레임워크들이 엄청난 리소스를 요구하는것과 뚜렷하게 대조됩니다. 추가적인 라이브러리는 필요할때만 동적으로 로드하시면 됩니다

CodeIgniter 는 빠릅니다

겁나빠릅니다. CodeIgniter 보다 빠른 프레임워크를 찾으신다면 오백원 드릴께요 .(미국으로 비행기타고오삼)

CodeIgniter 는 M-V-C 패턴에 기반합니다

CodeIgniter 는 모델-뷰-컨트롤러 패턴을 사용합니다. 비즈니스로직 계층과 표현계층이 분리되어있으므로 ,디자이너와 같이 일하실때 템플릿파일에는 최소한의 프로그램코드만 들어갈것입니다.

CodeIgniter 는 깔끔한 URL을 생성합니다

CodeIgniter 에서 생성한 URL 은 깔끔하고 검색엔진에서 색인되기 좋은 구조입니다. 일반적인 쿼리스트링 기반의 URL 이 아니라 세그먼트 기반의 URL 을 사용합니다.

example.com/news/article/345

위의경우 기본으로 index.php가 URL 에 포함되어있으나 , 간단히 .htaccess 파일을 사용하여 제거할수 있습니다.

CodeIgniter 는 굉장히 위력적입니다

CodeIgniter 는 일반적인 웹작업의 대부분을 커버하는 라이브러리를 제공합니다. 예를들어 database 접근,email 전송, form 데이터검증(validation),세션관리, 이미지 처리, XML-RPC 사용등을 제공합니다

 

CodeIgniter 는 확장 가능합니다

직접만든 라이브러리나 헬퍼 사용하여 손쉽게 확장할수있습니다.

혹은 클래스확장이나 시스템 후킹을 통해서도 확장가능합니다.

CodeIgniter 는 템플릿 엔진이 필요없습니다

CodeIgniter 가 심플한 템플릿파서를 포함하고있긴하지만, 반드시 사용할 필요는 없습니다. 템플릿엔진은 PHP 문법과 간단히 매치되지않기 때문에 거의 PHP를 배우는 만큼의 학습노력이 필요합니다.

아래 코드를 보시죠.

<ul>

<?php foreach ($addressbook as $name):?>

<li><?=$name?></li>

<?php endforeach; ?>

</ul>

아래는 템플릿 엔진을 사용할 경우 입니다

<ul>

{foreach from=$addressbook item="name"}

<li>{$name}</li>

{/foreach}

</ul>

맞습니다 맞구요.

템플릿엔진쪽이 쬐금 더 깨끗해보이긴합니다. 그러나 위 코드는 반드시 재해석의 과정을 거쳐야하기 때문에 성능이 떨어집니다. 우리의 목표는 최대의 성능이기 때문에 템플릿엔진을 사용하지 않습니다.

CodeIgniter 는 완벽하게 문서화 되어있습니다

개발자는 코드를 사랑하지 문서작성을 사랑하진 않습니다. 물론 우리도 별로 다르지않습니다.

그렇지만, 문서도 코드 자체만큼 중요하기 때문에 우리는 문서를 만들었답니다. 물론 코드도 깨끗할 뿐 아니라주석처리도 잘되었구요 .

CodeIgniter 는 친절한 사용자 커뮤니티가 있습니다.

포럼으로 오세요 -->Community Forums.

CodeIgniter Cheatsheets : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


CodeIgniter Cheatsheets

Library Reference

CodeIgniter Library Reference

Helpers Reference

CodeIgniter Library Reference
CodeIgniter Features : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


제공하는 기능목록(특징)CodeIgniter Features

특징만으로는 어플리케이션이 얼마나 쓰기좋고 똑똑하게 디자인되어있는지 알지못합니다.

특징은 코드의 품질이나 성능, 실용적 보안등을 판단하는데도 별 도움이 못됩니다.

어플리케이션이 좋은지 어떤지 알아보는 유일한 방법은 써보는것입니다.

CodeIgniter를 설치하는것은 거의 애들 장난만큼 쉽기 때문에 직접 써보실것을 권장드립니다.

 

Getting Started With CodeIgniter : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


시작하기 Getting Started With CodeIgniter

어떤 프로그램이라도 배우기위해서는 어느정도 노력이필요합니다. 즐거운 개발을 위해 우리는 배울것을 최소화하도록 노력했습니다.

먼저 CodeIgniter 를 설치하신후 CI 소개 항목을 읽어주세요.

다음으로 일반 토픽 항목을 순서대로 읽어주세요 . 각항목은 이전항목을 기반으로 전개됩니다. 그리고 포함되어있는 코드샘플은 따라해 보시길 권장합니다.

기본을 이해하셨다면 이제 클래스 레퍼런스와 헬퍼 레퍼런스를 읽으실 준비가 되신겁니다.

위 두가지 레퍼런스에서 어떻게 라이브러리와 헬퍼파일들을 활용하실지 알게 되실겁니다.

문제나 의문이 있다면 언제든지 포럼 이나 위키 에 물어보시고 또 이전 질답들도 확인하세요 .

Helper Functions : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


헬퍼 Helper Functions

헬퍼는 여러분의 일에 뭔가를 제안하고 도와주는 존재입니다. 각각의 헬퍼파일은 특정 영역에 해당하는 함수들의 모음입니다.예를 들어 URL 헬퍼 의 경우 링크생성을 도와주며,Form 헬퍼는 폼의요소를 만드는데 도움이 되고, Text 헬퍼는 다양한 텍스트 처리(formatting)을 도와주며, Cookie 헬퍼는 쿠키를 읽고 쓰는데, File 헬퍼는 파일을 조작하는데 도움이 될것입니다.

CodeIgniter의 다른 시스템과는 다르게 ,헬퍼는 객체지향적인 형태로 작성되지않았습니다.헬퍼의 함수들은 간단하고 ,절차적입니다. 각 헬퍼 함수들은 특정한 한가지 일만하며 ,다른 헬퍼함수에 의존하지않습니다.

CodeIgniter 는 헬퍼를 자동으로 로드하지않으므로 ,사용을 위해서는 먼저 해당 헬퍼를 로드해야합니다. 한번로드되면 여러분의컨트롤러에서 글로벌 하게 사용할 수 있습니다. .

헬퍼는 통상system/helpers폴더나 application/helpers 폴더에 위치합니다. CodeIgniter 는 application/helpers 폴더를 먼저 살펴볼것입니다. 해당디렉토리가 없거나, 해당디렉토리에 찾는 헬퍼가 없다면 CI는 글로벌 헬퍼가 저장되어있는 system/helpers 폴더를 살펴볼것입니다.

헬퍼 로드하기

헬퍼를 로드하는것은 다음예제처럼 매우 간단합니다:

$this->load->helper('name');

name 은 헬퍼파일 이름을 가리키며 .php 확장자 및 _helper 는 붙이지 않습니다.

예를 들어 URL 헬퍼 를 로드할경우, url_helper.php 라는 파일이므로 다음과 같이로드합니다:

$this->load->helper('url');

헬퍼는 사용하기전에 반드시 먼저 로드해야하며 컨트롤러의 어느함수안에서 로드해도 상관없습니다. 심지어 뷰파일 안에서도 로드할수있습니다만 권장하지않습니다. 헬퍼를 컨트롤러의 생성자에서 로드해두면 컨트롤러 내부의 어떤 함수에서도 바로 사용할 수 있습니다.그렇지않으면 헬퍼가 필요한 해당 함수에서 로드하여 사용하셔도 됩니다..

Note: 헬퍼를 로드하는 것은 리턴값이 없으므로 리턴값을 저장하기위하여 변수에 할당하지 마시기 바랍니다.그저 위의 예시처럼 사용하시면 됩니다..

여러개의 헬퍼 로드하기

여러개의 헬퍼를 로드해야할경우 ,아래와같이 배열을 이용할 수 있습니다:

$this->load->helper( array('helper1', 'helper2', 'helper3') );

헬퍼 자동 로드

헬퍼가 프로그램 전반에 광범위하게 쓰여야한다면 자동로드 설정으로 시스템 초기화 과정에서 자동으로 로드할 수 있습니다.application/config/autoload.php 파일을 연다음 autoload 배열에 해당 헬퍼를 추가해주세요.

헬퍼사용하기

헬퍼는 일단 한번 로드 되면 ,표준 PHP 함수를 사용하듯 사용하면 됩니다..

예를 들어 anchor() 함수를 이용하여 링크(< a 태그)를 생성한다면 View 파일에서 다음과같이 사용할 수 있습니다.:

<?php echo anchor('blog/comments', 'Click Here');?>

"Click Here" 은 이름( <a 태그 안에 name 속성)이 되고 "blog/comments" 는 연결하고자하는 url 이 됩니다.이 URL 은 통상 controller/function 형태를 가지게 되겠죠.

헬퍼의 확장

헬퍼를 확장하려면application/helpers/ 폴더아래 기존 헬퍼와 겹치지않는 이름의 파일을 만듦니다.이 때 이름의 접두어는 MY_ 가 되어야합니다.(이부분은 설정이 가능합니다. 아래를 보세요).

기존헬퍼에 두어개의 함수를 추가할경우 헬퍼를 새로 작성하는것은 낭비입니다. 이런경우 기존의 헬퍼를 상속(extends)하는것이 현명합니다.상속(extend)라는 말은 대략적으로 사용하겠습니다. 왜냐하면 헬퍼함수는 절차적이며따로따로 작용하기 때문입니다. 헬퍼는 전통적인 프로그램 기법과는 다르게 상속(extends) 됩니다. 이방법을 통해서 기존의 헬퍼에 기능을 추가하거나 기존기능을 수정할 수 있게됩니다.

예를들어 내장된 Array Helper 를 사용할경우 application/helpers/MY_array_helper.php 파일을 생성하고 함수를 추가하거나 재정의합니다.:

// any_in_array() is not in the Array Helper, so it defines a new function
function any_in_array($needle, $haystack)
{
    $needle = (is_array($needle)) ? $needle : array($needle);

    foreach ($needle as $item)
    {
        if (in_array($item, $haystack))
        {
            return TRUE;
        }
        }

    return FALSE;
}

// random_element() is included in Array Helper, so it overrides the native function
function random_element($array)
{
    shuffle($array);
    return array_pop($array);
}

나만의 접두어 설정하기

파일명의 접두어는 헬퍼에도 쓰이지만,라이브러리 및 코어클래스를 확장할때에도 쓰입니다. 나만의 접두어를 설정하려면 application/config/config.php 에서 아래의 아이템을 찾은후 설정하시면됩니다.

$config['subclass_prefix'] = 'MY_';

모든 CodeIgniter 내장 라이브러리의 접두어는CI_ 이므로 나만의 접두어로 사용할수 없습니다.

이제 뭐하지?

목차페이지에서 다양한 헬퍼를 만나실수 있습니다.

Creating Drivers : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


드라이버 생성

드라이버의 디렉토리 및 파일 구조

샘플 드라이버의 디렉토리및 파일 구조 레이아웃:

주의: Driver_nameucfirst()를 적용하여 , 대소문자를 구분하는 시스템에서도 문제 없도록 하세요.

Style Guide : CodeIgniter User Guide

CodeIgniter User Guide Version 2.1.0


General Style and Syntax

The following page describes the use of coding rules adhered to when developing CodeIgniter.

Table of Contents

  • File Format

    Files should be saved with Unicode (UTF-8) encoding. The BOM should not be used. Unlike UTF-16 and UTF-32, there's no byte order to indicate in a UTF-8 encoded file, and the BOM can have a negative side effect in PHP of sending output, preventing the application from being able to set its own headers. Unix line endings should be used (LF).

    Here is how to apply these settings in some of the more common text editors. Instructions for your text editor may vary; check your text editor's documentation.

    TextMate
    1. Open the Application Preferences
    2. Click Advanced, and then the "Saving" tab
    3. In "File Encoding", select "UTF-8 (recommended)"
    4. In "Line Endings", select "LF (recommended)"
    5. Optional: Check "Use for existing files as well" if you wish to modify the line endings of files you open to your new preference.
    BBEdit
    1. Open the Application Preferences
    2. Select "Text Encodings" on the left.
    3. In "Default text encoding for new documents", select "Unicode (UTF-8, no BOM)"
    4. Optional: In "If file's encoding can't be guessed, use", select "Unicode (UTF-8, no BOM)"
    5. Select "Text Files" on the left.
    6. In "Default line breaks", select "Mac OS X and Unix (LF)"

    PHP Closing Tag

    The PHP closing tag on a PHP document ?> is optional to the PHP parser. However, if used, any whitespace following the closing tag, whether introduced by the developer, user, or an FTP application, can cause unwanted output, PHP errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should OMIT the closing PHP tag, and instead use a comment block to mark the end of file and it's location relative to the application root. This allows you to still identify a file as being complete and not truncated.

    INCORRECT: <?php echo "Here's my code!"; ?> CORRECT: <?php echo "Here's my code!"; /* End of file myfile.php */ /* Location: ./system/modules/mymodule/myfile.php */

    Class and Method Naming

    Class names should always start with an uppercase letter. Multiple words should be separated with an underscore, and not CamelCased. All other class methods should be entirely lowercased and named to clearly indicate their function, preferably including a verb. Try to avoid overly long and verbose names.

    INCORRECT: class superclass class SuperClass CORRECT: class Super_class class Super_class { function __construct() { } }

    Examples of improper and proper method naming:

    INCORRECT: function fileproperties() // not descriptive and needs underscore separator function fileProperties() // not descriptive and uses CamelCase function getfileproperties() // Better! But still missing underscore separator function getFileProperties() // uses CamelCase function get_the_file_properties_from_the_file() // wordy CORRECT: function get_file_properties() // descriptive, underscore separator, and all lowercase letters

    Variable Names

    The guidelines for variable naming is very similar to that used for class methods. Namely, variables should contain only lowercase letters, use underscore separators, and be reasonably named to indicate their purpose and contents. Very short, non-word variables should only be used as iterators in for() loops.

    INCORRECT: $j = 'foo'; // single letter variables should only be used in for() loops $Str // contains uppercase letters $bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning $groupid // multiple words, needs underscore separator $name_of_last_city_used // too long CORRECT: for ($j = 0; $j < 10; $j++) $str $buffer $group_id $last_city

    Commenting

    In general, code should be commented prolifically. It not only helps describe the flow and intent of the code for less experienced programmers, but can prove invaluable when returning to your own code months down the line. There is not a required format for comments, but the following are recommended.

    DocBlock style comments preceding class and method declarations so they can be picked up by IDEs:

    /** * Super Class * * @package Package Name * @subpackage Subpackage * @category Category * @author Author Name * @link http://example.com */ class Super_class { /** * Encodes string for use in XML * * @access public * @param string * @return string */ function xml_encode($str)

    Use single line comments within code, leaving a blank line between large comment blocks and code.

    // break up the string by newlines $parts = explode("\n", $str); // A longer comment that needs to give greater detail on what is // occurring and why can use multiple single-line comments. Try to // keep the width reasonable, around 70 characters is the easiest to // read. Don't hesitate to link to permanent external resources // that may provide greater detail: // // http://example.com/information_about_something/in_particular/ $parts = $this->foo($parts);

    Constants

    Constants follow the same guidelines as do variables, except constants should always be fully uppercase. Always use CodeIgniter constants when appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc.

    INCORRECT: myConstant // missing underscore separator and not fully uppercase N // no single-letter constants S_C_VER // not descriptive $str = str_replace('{foo}', 'bar', $str); // should use LD and RD constants CORRECT: MY_CONSTANT NEWLINE SUPER_CLASS_VERSION $str = str_replace(LD.'foo'.RD, 'bar', $str);

    TRUE, FALSE, and NULL

    TRUE, FALSE, and NULL keywords should always be fully uppercase.

    INCORRECT: if ($foo == true) $bar = false; function foo($bar = null) CORRECT: if ($foo == TRUE) $bar = FALSE; function foo($bar = NULL)

    Logical Operators

    Use of || is discouraged as its clarity on some output devices is low (looking like the number 11 for instance). && is preferred over AND but either are acceptable, and a space should always precede and follow !.

    INCORRECT: if ($foo || $bar) if ($foo AND $bar) // okay but not recommended for common syntax highlighting applications if (!$foo) if (! is_array($foo)) CORRECT: if ($foo OR $bar) if ($foo && $bar) // recommended if ( ! $foo) if ( ! is_array($foo))

    Comparing Return Values and Typecasting

    Some PHP functions return FALSE on failure, but may also have a valid return value of "" or 0, which would evaluate to FALSE in loose comparisons. Be explicit by comparing the variable type when using these return values in conditionals to ensure the return value is indeed what you expect, and not a value that has an equivalent loose-type evaluation.

    Use the same stringency in returning and checking your own variables. Use === and !== as necessary. INCORRECT: // If 'foo' is at the beginning of the string, strpos will return a 0, // resulting in this conditional evaluating as TRUE if (strpos($str, 'foo') == FALSE) CORRECT: if (strpos($str, 'foo') === FALSE) INCORRECT: function build_string($str = "") { if ($str == "") // uh-oh! What if FALSE or the integer 0 is passed as an argument? { } } CORRECT: function build_string($str = "") { if ($str === "") { } }

    See also information regarding typecasting, which can be quite useful. Typecasting has a slightly different effect which may be desirable. When casting a variable as a string, for instance, NULL and boolean FALSE variables become empty strings, 0 (and other numbers) become strings of digits, and boolean TRUE becomes "1":

    $str = (string) $str; // cast $str as a string

    Debugging Code

    No debugging code can be left in place for submitted add-ons unless it is commented out, i.e. no var_dump(), print_r(), die(), and exit() calls that were used while creating the add-on, unless they are commented out.

    // print_r($foo);

    Whitespace in Files

    No whitespace can precede the opening PHP tag or follow the closing PHP tag. Output is buffered, so whitespace in your files can cause output to begin before CodeIgniter outputs its content, leading to errors and an inability for CodeIgniter to send proper headers. In the examples below, select the text with your mouse to reveal the incorrect whitespace.

    INCORRECT:

    <?php // ...there is whitespace and a linebreak above the opening PHP tag // as well as whitespace after the closing PHP tag ?>

    CORRECT:

    <?php // this sample has no whitespace before or after the opening and closing PHP tags ?>

    Compatibility

    Unless specifically mentioned in your add-on's documentation, all code must be compatible with PHP version 5.1+. Additionally, do not use PHP functions that require non-default libraries to be installed unless your code contains an alternative method when the function is not available, or you implicitly document that your add-on requires said PHP libraries.

    Class and File Names using Common Words

    When your class or filename is a common word, or might quite likely be identically named in another PHP script, provide a unique prefix to help prevent collision. Always realize that your end users may be running other add-ons or third party PHP scripts. Choose a prefix that is unique to your identity as a developer or company.

    INCORRECT: class Email pi.email.php class Xml ext.xml.php class Import mod.import.php CORRECT: class Pre_email pi.pre_email.php class Pre_xml ext.pre_xml.php class Pre_import mod.pre_import.php

    Database Table Names

    Any tables that your add-on might use must use the 'exp_' prefix, followed by a prefix uniquely identifying you as the developer or company, and then a short descriptive table name. You do not need to be concerned about the database prefix being used on the user's installation, as CodeIgniter's database class will automatically convert 'exp_' to what is actually being used.

    INCORRECT: email_addresses // missing both prefixes pre_email_addresses // missing exp_ prefix exp_email_addresses // missing unique prefix CORRECT: exp_pre_email_addresses

    NOTE: Be mindful that MySQL has a limit of 64 characters for table names. This should not be an issue as table names that would exceed this would likely have unreasonable names. For instance, the following table name exceeds this limitation by one character. Silly, no? exp_pre_email_addresses_of_registered_users_in_seattle_washington

    One File per Class

    Use separate files for each class your add-on uses, unless the classes are closely related. An example of CodeIgniter files that contains multiple classes is the Database class file, which contains both the DB class and the DB_Cache class, and the Magpie plugin, which contains both the Magpie and Snoopy classes.

    Whitespace

    Use tabs for whitespace in your code, not spaces. This may seem like a small thing, but using tabs instead of whitespace allows the developer looking at your code to have indentation at levels that they prefer and customize in whatever application they use. And as a side benefit, it results in (slightly) more compact files, storing one tab character versus, say, four space characters.

    Line Breaks

    Files must be saved with Unix line breaks. This is more of an issue for developers who work in Windows, but in any case ensure that your text editor is setup to save files with Unix line breaks.

    Code Indenting

    Use Allman style indenting. With the exception of Class declarations, braces are always placed on a line by themselves, and indented at the same level as the control statement that "owns" them.

    INCORRECT: function foo($bar) { // ... } foreach ($arr as $key => $val) { // ... } if ($foo == $bar) { // ... } else { // ... } for ($i = 0; $i < 10; $i++) { for ($j = 0; $j < 10; $j++) { // ... } } CORRECT: function foo($bar) { // ... } foreach ($arr as $key => $val) { // ... } if ($foo == $bar) { // ... } else { // ... } for ($i = 0; $i < 10; $i++) { for ($j = 0; $j < 10; $j++) { // ... } }

    Bracket and Parenthetic Spacing

    In general, parenthesis and brackets should not use any additional spaces. The exception is that a space should always follow PHP control structures that accept arguments with parenthesis (declare, do-while, elseif, for, foreach, if, switch, while), to help distinguish them from functions and increase readability.

    INCORRECT: $arr[ $foo ] = 'foo'; CORRECT: $arr[$foo] = 'foo'; // no spaces around array keys INCORRECT: function foo ( $bar ) { } CORRECT: function foo($bar) // no spaces around parenthesis in function declarations { } INCORRECT: foreach( $query->result() as $row ) CORRECT: foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis

    Localized Text

    Any text that is output in the control panel should use language variables in your lang file to allow localization.

    INCORRECT: return "Invalid Selection"; CORRECT: return $this->lang->line('invalid_selection');

    Private Methods and Variables

    Methods and variables that are only accessed internally by your class, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore.

    convert_text() // public method _convert_text() // private method

    PHP Errors

    Code must run error free and not rely on warnings and notices to be hidden to meet this requirement. For instance, never access a variable that you did not set yourself (such as $_POST array keys) without first checking to see that it isset().

    Make sure that while developing your add-on, error reporting is enabled for ALL users, and that display_errors is enabled in the PHP environment. You can check this setting with:

    if (ini_get('display_errors') == 1) { exit "Enabled"; }

    On some servers where display_errors is disabled, and you do not have the ability to change this in the php.ini, you can often enable it with:

    ini_set('display_errors', 1);

    NOTE: Setting the display_errors setting with ini_set() at runtime is not identical to having it enabled in the PHP environment. Namely, it will not have any effect if the script has fatal errors

    Short Open Tags

    Always use full PHP opening tags, in case a server does not have short_open_tag enabled.

    INCORRECT: <? echo $foo; ?> <?=$foo?> CORRECT: <?php echo $foo; ?>

    One Statement Per Line

    Never combine statements on one line.

    INCORRECT: $foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag); CORRECT: $foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag);

    Strings

    Always use single quoted strings unless you need variables parsed, and in cases where you do need variables parsed, use braces to prevent greedy token parsing. You may also use double-quoted strings if the string contains single quotes, so you do not have to use escape characters.

    INCORRECT: "My String" // no variable parsing, so no use for double quotes "My string $foo" // needs braces 'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly CORRECT: 'My String' "My string {$foo}" "SELECT foo FROM bar WHERE baz = 'bag'"

    SQL Queries

    MySQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, AS, JOIN, ON, IN, etc.

    Break up long queries into multiple lines for legibility, preferably breaking for each clause.

    INCORRECT: // keywords are lowercase and query is too long for // a single line (... indicates continuation of line) $query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses ...where foo != 'oof' and baz != 'zab' order by foobaz limit 5, 100"); CORRECT: $query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz FROM exp_pre_email_addresses WHERE foo != 'oof' AND baz != 'zab' ORDER BY foobaz LIMIT 5, 100");

    Default Function Arguments

    Whenever appropriate, provide function argument defaults, which helps prevent PHP errors with mistaken calls and provides common fallback values which can save a few lines of code. Example:

    function foo($bar = '', $baz = FALSE)
  • Running via the CLI : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    CLI에서 실행

    브라우저의 url을 통해서 Controllers 를 호출할 수 있는것과 마찬가지로 명령줄 the command-line interface (CLI)에서도 호출 할 수있습니다.

    CLI란?

    command-line interface 는 명령줄에서 프로그램을 실행하는것임(다들 아실듯). 더 궁금하시다면 위키페이지를 보삼 -> Wikipedia article.

    왜 명령줄에서 실행하는가?

    명령줄에서 CodeIgniter를 실행하는 이유는 여러가지가 있지만 명확한 이유가 없는 경우도 있겠습니다요.

    해 봅시다:  Hello World!

    실제 동작을 확인하기 위해 간단한 컨트롤러를 작성합시다. 텍스트 편집기에서tools.php 를 만들고 다음 코드를 입력하십시오:

    그런 다음이 파일을 application/controllers/ 폴더에 저장합니다.

    일반적으로 다음의 URL에 액세스하여 사이트를 볼 수 있습니다.:

    example.com/index.php/tools/message/to

    CodeIgniter 프로젝트를 조작하기 위해 Mac / Linux에서는 터미널을 열고 Windows에서는 "cmd"를 실행합니다.

    $ cd /path/to/project;
    $ php index.php tools message

    제대로 했다면 Hello World!를 보실 수 있습니다.

    $ php index.php tools message "John Smith"

    URL 인수와 마찬가지로 인수를 전달할 수 있습니다. "John Smith"를 인수로 전달하여 다음과 같이 표시됩니다. : Hello John Smith!.

    이것이 전부입니다!

    위에것만 알면 명령줄에서 controller를 사용하는데 문제가 없습니다. 라우팅이나_remap 도 문제 없이 동작합니다.

    Profiling Your Application : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    프로파일링 Profiling Your Application

    프로파일러 클래스는 벤치마크결과,여러분이 수행한 쿼리,$_POST 데이터를 여러분의 페이지 하단에 보여줄것입니다..

    이런 정보들은 개발시 디버깅이나 최적화 작업을 하는데 도움이 될 것입니다..

    클래스 초기화

    Important:  본 클래스는 초기화가 필요없습니다.만약 아래에서 설명하는 대로 프로파일링이 활성(enable)화 되어있다면 출력클래스(Output Class)i에서 자동으로 초기화됩니다.

    프로파일링 활성화(Enabling the Profiler)

    프로파일링을 활성화 하려면 아래와같은 코드를 여러분 컨트롤러의 어떤 곳에서든지 삽입하시면 됩니다.:

    $this->output->enable_profiler(TRUE);

    활성화 되면 리포트가 생성되고 여러분 페이지의 하단에 삽입됩니다.

    프로파일링을 비활성화 하려면 아래의 코드를 삽입하세요.:

    $this->output->enable_profiler(FALSE);

    벤치마크 포인트 설정(Setting Benchmark Points)

    프로파일러가 벤치마크 결과를 컴파일 하기위해서는 특정한 문법으로 벤치마크 포인트를 지정해 주어야합니다.

    벤치마크 포인트 설정에 관해서는 벤치마크(Benchmark Class) 페이지를 참고하세요

    프로파일 섹션의 활성화 및 비활성화

    각 섹션의 프로파일 데이타를 활성/비활성화 하려면, 해당 설정값을 TRUEFALSE로 설정하세요. 설정에는 두가지 방법이 있습니다.응용프로그램 단위로 설정하려면 application/config/profiler.php 에서 하세요.

    $config['config']          = FALSE;
    $config['queries']         = FALSE;

    컨트롤러에서 출력클래스set_profiler_sections()를 호출하면 설정된 기본값 덮어 쓸 수 있습니다:

    $sections = array(
        'config'  => TRUE,
        'queries' => TRUE
        );

    $this->output->set_profiler_sections($sections);

    사용 가능한 섹션과 필요한 배열의 키는 다음의 표와 같습니다.

    설명 기본값
    benchmarks 벤치 마크 포인트에서 경과 시간과 총 실행 시간 TRUE
    config CodeIgniter 설정 변수 TRUE
    controller_info 요청된 컨트롤러 클래스와 메소드 TRUE
    get 요청에 전달된 모든 GET 데이터 TRUE
    http_headers 현재 요청의 HTTP 헤더 TRUE
    memory_usage 현재 요청에서 사용된 메모리 용량(Bytes) TRUE
    post 요청에 전달된 모든 POST 데이터 TRUE
    queries 실행 시간을 포함하여 실행된 모든 데이터베이스 쿼리 목록 TRUE
    uri_string 현재 요청 URI TRUE
    query_toggle_count 숨길 쿼리블록수 의 기본 값 설정 25
    Error Handling : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    에러 핸들링Error Handling

    CodeIgniter 는 아래 함수들을 이용하여 여러분 프로그램에서 에러에 대한 리포트를 생성하도록 지원합니다.게다가,에러 로깅(error logging )클래스도 제공합니다. 에러로깅 클래스를 이용하면 에러를 텍스트 파일로 저장할 수 있습니다.

    Note: CodeIgniter의 기본설정은 모든 PHP 에러를 표시하는 것입니다. 그런데 님하의 프로그램 개발이 완료되었을때 이런 기본 설정을 변경하고 싶을 수 있습니다. 메인 index.php 의 맨윗쪽에 error_reporting() 함수가 있습니다. error reporting 을 disable 하는것이 에러 로그파일을 기록하는것 까지 disable 하지는 않습니다.

    대부분 CodeIgniter의 시스템과는달리 ,에러 함수는 절차적 인터페이스를 가지며 프로그램 전반에 걸쳐 글로벌 하게 사용할 수 있다.

    이런 접근방법은 클래스나 함수의 스코프에 상관없이 에러 메시지를 생성하게 해줍니다.

    다음 함수는 에러를 생성하도록 해줍니다.:

    show_error('message')

    이 함수는 아래 템플릿을 이용하여 에러메세지를 표시합니다.:

    application/errors/error_general.php

    show_404('page' [, 'log_error'])

    이 함수는 아래 템플릿을 이용하여 404 에러메세지를 표시합니다.

    application/errors/error_404.php

    이 함수는 발견되지않은(not found) 페이지의 경로를 문자열로 전달받을것을 가정합니다.

    주의 : CodeIgniter 는 컨트롤러를 발견할 수 없으면 자동적으로 404 에러메세지를 표시합니다.

    모든 show_404() 호출은 로그에 기록됩니다. 두번째 파라미터를 FALSE 로 하면 로그에 기록하지 않습니다.

    log_message('level', 'message')

    이함수는 로그파일에 에러메세지를 쓸수 있도록 합니다. 먼저 3개의 에러타입(debug, error, info)중 하나의 타입을 첫번째 파라미터로 전달해야합니다.메세지는 두번째 파라미터로 전달합니다.

    예제:

    if ($some_var == "")
    {
        log_message('error', 'Some variable did not contain a value.');
    }
    else
    {
        log_message('debug', 'Some variable was correctly set');
    }

    log_message('info', 'The purpose of some variable is to provide some value.');

    3가지 메세지 타입이 있습니다:

    1. Error 메세지 : PHP 에러나 사용자 에러등 진짜 에러 메시지.
    2. Debug 메세지: 디버그를 도와주는 메세지.예를 들어, 클래스가 초기화되면 님하는 debugging 정보로 파일에 기록할 수 있습니다.
    3. Informational 메세지 : 이 메시지는 가장 우선순위가 낮은 메세지 . 단순히 어떤 프로세스에 대한 메세지를 제공합니다. CodeIgniter 는 Info 메세지를 작성하지않습니다만, 님하가 원하시는 메세지를 스스로 기록하실수있습니다.

    Note: 로그파일을 기록하려면 "logs" 폴더에 쓰기권한이 있어야합니다.또한 , application/config/config.php에서 쓰레스홀드("threshold)를 먼저 세팅해야합니다.예를 들어 , 에러메세지만 기록하고 싶을수도 있겠죠 ?. 제로로 세팅하시면 로깅은 비활성화(disabled) 될것입니다.

    Models : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    모델Models

    모델은 전통적인 MVC 패턴을 구현하고자하는사람들이 선택적으로 사용할 수 있습니다.

    What is a Model?

    모델은 데이터베이스와 연동하여 사용하기위한 PHP 클래스입니다. 예를들이, CodeIgniter 를 이용하여 블로그를 관리한다고합시다. 아마 삽입,조회,수정 등의 기능을 가진 모델클래스가 필요할것입니다.

    모델클래스의 형태 예제:

    class Blogmodel extends CI_Model {

        var $title   = '';
        var $content = '';
        var $date    = '';

        function __construct()
        {
            // Call the Model constructor
            parent::__construct();
        }
        
        function get_last_ten_entries()
        {
            $query = $this->db->get('entries', 10);
            return $query->result();
        }

        function insert_entry()
        {
            $this->title   = $_POST['title']; // please read the below note
            $this->content = $_POST['content'];
            $this->date    = time();

            $this->db->insert('entries', $this);
        }

        function update_entry()
        {
            $this->title   = $_POST['title'];
            $this->content = $_POST['content'];
            $this->date    = time();

            $this->db->update('entries', $this, array('id' => $_POST['id']));
        }

    }

    Note: 위의 함수들은 액티브레코드(Active Record) 를 이용하여 데이터베이스를 이용하는 방법을 보여줍니다

    Note: 이예제에서는 단순화하기위하여 $_POST 를 바로 사용하였습니다. 일반적으로는 나쁜예죠. 일반적인 접근법은 Input 클래스 를 다음과 같이 사용하는것 입니다 .$this->input->post('title')

    모델의 해부

    모델클래스는application/models/ 폴더에 저장됩니다. 서브폴더에 저장하셔도 됩니다.

    모델클래스의 기본 프로토 타입예:

    class Model_name extends CI_Model {

        function __construct()
        {
            parent::__construct();
        }
    }

    Model_name 은 여러분의 클래스 이름으로 바꾸세요. 클래스이름의 첫글자는 반드시 대문자로 시작해야하며 나머지 글자들은 소문자라야 합니다. 여러분의 클래스는 반드시 Model 클래스에서 상속(extends)받아야 합니다.

    파일명은 클래스명과 같아야하나 모두 소문자여야 합니다.

    예를들어 클래스가 아래와같다면:

    class User_model extends CI_Model {

        function __construct()
        {
            parent::__construct();
        }
    }

    파일명은 아래와 같아야합니다:

    application/models/user_model.php

    모델 로드하기

    모델은 일반적으로 컨트롤러 내에서 로드되어 호출됩니다. 모델은 아래와 같은 방법으로 로드합니다:

    $this->load->model('Model_name');

    모델이 하위폴더에 있다면 상대경로로 모델폴더를 적어줍니다.예를 들어 모델이 application/models/blog/queries.php 경로에 위치해있다면 아래와같이 로드할수 있습니다:

    $this->load->model('blog/queries');

    모델이 로드되면 모델클래스의 이름과 같은 객체로 모델내의 함수를 사용할수 있습니다.

    예제:

    $this->load->model('Model_name');

    $this->Model_name->function();

    모델을 다른객체이름으로 할당하여 사용하고싶다면 두번째 파라미터에 사용하고싶은 이름을 넘겨서 로드하시면됩니다예:

    $this->load->model('Model_name', 'fubar');

    $this->fubar->function();

    아래는 모델을 로드하여 그 데이터를 뷰에 넘겨주는 예제입니다:

    class Blog_controller extends CI_Controller {

        function blog()
        {
            $this->load->model('Blog');

            $data['query'] = $this->Blog->get_last_ten_entries();

            $this->load->view('blog', $data);
        }
    }

    모델 자동로드

    프로그램 전체에 걸쳐 글로벌로 모델을 로드해야할경우라면 자동로드 설정을 통해 자동으로 로드하도록 할수 있습니다. application/config/autoload.php 파일을 열어서 autoload 배열에 원하는 모델을 추가하세요.

    데이터베이스 연결

    모델이 로드되었을때 그 모델이 자동으로 데이터베이스에 연결하지는 않습니다.다음의 옵션을 사용하여 연결하세요.

    Reserved Names : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    CI 예약어 목록 Reserved Names

    CodeIgniter 에서는 아래와 같은 예약어가 있으므로 ,여러분은 개발시 사용할수 없습니다.

    컨트롤러 이름(Controller names)

    여러분의 컨트롤러는 부모클래스로부터 상속받아 작성되기때문에 부모클래스에서 사용하는 함수이름을 사용하지않도록 주의해야합니다. 그렇지않으면 부모클래스의 함수를 재정의 해버리기때문에 오작동 합니다.

    아래는 예약어 목록입니다. 아래 목록을 컨트롤러 이름으로 사용할 수 없습니다.


    함수명(Functions)

    변수명(Variables)

    상수명(Constants)

    Web Page Caching : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    캐싱 Web Page Caching

    성능의 극대화를 위해 CodeIgniter 는 여러분의 페이지를 캐싱할수 있도록 합니다..

    비록 CodeIgniter 가 대단히 빠르긴 하지만, 페이지에 표시하고자하는 동적 정보들이 서버의 리소스,메모리,처리사이클등과 직접적으로 연관되어있기때문에 페이지 로드 속도에 영향을 미칩니다.

    페이지를 캐싱하므로써 거의 정적 html 만큼 성능을 향상 시킬 수 있습니다.

     

    캐싱은 어떻게 작동하나요?

    캐싱은 페이지 단위로 활성화 시킬수 있으며 , 캐시가 얼마동안 존재하고 리프레쉬 될지 설정할 수 있습니다.

    페이지가 처음으로 로드되면 캐시파일은 application/cache 폴더에 작성됩니다. 이후에 같은 페이지가 요청되면 캐시파일이 브라우저로 전송됩니다. 캐시파일 존재시한이 지나면 캐시는 삭제되고 다시 작성될것입니다.

    Note: 벤치마크 태그는 캐시 되지않으므로 캐시가 활성(enable)화 된 상태에서도 페이지 로드 속도를 보실수 있습니다.

    캐싱 활성화

    캐시를 활성화 하려면 아래의 코드를 컨트롤러에서 원하는 위치에 삽입하세요.:

    $this->output->cache(n);

    n 은 캐시가 존재할 시간(리프레쉬 주기)을 분단위로 설정하는 값입니다.

    위 테그는 어떤 함수 안에서도 쓸수있습니다. 순서에 상관이 없으므로 논리적으로 맞는 위치에 삽입하시면 됩니다. 위 태그가 삽입되면 여러분의 페이지는 캐싱 될것입니다..

    Warning: 캐싱은 콘트롤러 와 뷰(view)를 같이 사용하여 페이지를 작성할 때만 작동합니다.

    Note: application/cache 폴더에 반드시 쓰기 권한이 있어야 합니다.

    캐시 삭제

    캐시가 더이상 필요없으면 캐시태그를 삭제하므로서 제거할수 있습니다. 캐시태그가 삭제되면 리프레쉬 주기가 돌아왔을때 기존 캐시를 삭제한후 다시 생성하지 않을것입니다.. Note: 캐시 태그를 삭제한다고 해서 캐시파일이 즉시 삭제되지는 않습니다. 즉시 삭제를 원하시면 캐시폴더에 있는 캐시파일을 직접 삭제하셔야 합니다.

    Alternate PHP Syntax for View Files : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    View 에서 PHP문법을 CI 문법으로 대체 Alternate PHP Syntax for View Files

    CodeIgniter의 템플릿엔진 을 사용하지않는다면 ,아마 님하는 View 파일에서 순수 PHP 를 쓰실겁니다. 뷰 파일에서 PHP 코드를 최소화 하기위해서 루프등 코드 블록에서는 PHP 대체문법을 사용하시고 , echo 문의 경우에는 단축태그를 사용하시길 권장합니다. 여러분이 이런 문법에 익숙하지않았다면, 이 문법은 여러분의 코드에서 대괄호(brace)를 제거해주고 echo 문을 제거해줄것입니다.

    자동화된 짧은 태그 지원 Automatic Short Tag Support

    Note: 본페이지에서 설명하는 문법이 당신의 서버에서는 작동하지 않는다면, 아마 php.ini 파일에서 짧은태그(short tags) 가 비활성화(disabled)되어있기 때문일것입니다.CodeIgniter는 만약 서버에서 지원하지않는다고해도 본페이지의 문법을 사용할 수 있도록 옵션을 제공합니다. 해당 옵션을 적용하면 짧은태그(short tags)를 즉석해서 다시 쓸것(rewrite)입니다. 이 옵션은 config/config.php 파일에서 설정 할 수 있습니다.

    주의 : 만약 이 옵션을 사용하지 않으시면, 뷰(View)파일에서 PHP 에러가 발생했을때 , 에러메시지와 줄번호가 정확하게 표시되지 않을것입니다. 대신에 모든 에러는 eval() 에러처럼 표시될것입니다.

    에코문 대체 Alternative Echos

    일번적으로 에코문을 사용하여 변수를 출력하려면 아래와 같이 할것입니다:

    <?php echo $variable; ?>

    대체문법은 아래와 같습니다.:

    <?=$variable?>

    대체 분기,루프 구조 Alternative Control Structures

    if, for, foreachwhile 과 같은 분기, 루프 구조 또한 단순한 구조로 사용될 수 있습니다.아래는 foreach 문의 예제입니다:

    <ul>

    <?php foreach($todo as $item): ?>

    <li><?=$item?></li>

    <?php endforeach; ?>

    </ul>

    보시는 바와 같이 중괄호가 없고 대신 괄호 닫는부분이 endforeach로 변경되었습니다. 앞에 나열된 각종 분기,루프 구조는 유사한 구조를 가집니다.닫는괄호 부분은 endif, endfor, endforeach, endwhile 를 사용하시면 됩니다.

    또한 각 구조 뒤에 세미콜론이 아닌 콜론을 사용한다는점을 주의하세요(끝부분 제외).

    if 문을 사용하는 예제입니다.콜론에 주목해 주세요:

    <?php if ($username == 'sally'): ?>

       <h3>Hi Sally</h3>

    <?php elseif ($username == 'joe'): ?>

       <h3>Hi Joe</h3>

    <?php else: ?>

       <h3>Hi unknown user</h3>

    <?php endif; ?>
    Creating Core System Classes : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    나만의 코어 클래스 만들기 Creating Core System Classes

    CodeIgniter를 사용할때마다 자동으로 초기화되어 코어프레임워크의 일부로 작동하는 몇몇 기반클래스(base classes)가 있습니다. 그것도 좋습니다만, 코어클래스를 여러분의 클래스로 대체하거나 확장 하는것도 가능합니다.

     

    대부분 사용자들은 이런것까지 필요없겠지만, 깊이있게 CodeIgniter 의 코어부분을 튜닝하고싶어하는분들을 위해 이러한 옵션을 제공합니다.

    Note: 코어클래스에대해 작업하는것은 여러가지 위험을 내포하고있으므로, 매우 신중하셔야 합니다.

    시스템 클래스 목록

    다음의 시스템클래스 목록은 CodeIgniter가 작동할때마다 호출되는 클래스 들입니다.:

    코어클래스 대체 Replacing Core Classes

    내장된 코어클래스 대신에 당신이 만든 시스템 클래스를 사용하려면 클래스 파일을 application/core 폴더에 저장하세요:

    application/core/some-class.php

    이 폴더가 없다면 만드시면 됩니다..

    당신의 클래스 이름이 상단의 클래스 목록중 어느하나와 일치한다면 당신의 클래스가 그것 대신 사용될 것입니다..

    당신의 클래스선언은 는 반드시 CI 접두어로 시작해야합니다.. 예를 들어 ,당신이 만든 파일 이름이 Input.php 이라면 클래스는 다음과 같이 선언해야합니다.:

    class CI_Input {

    }

    코어클래스 확장

    내장 코어 클래스에 몇몇 함수추가 정도를 원하신다면 내장클래스를 확장하는것이 현명합니다..클래스 확장 작업은 대체작업과 거의 유사합니다.

    예를들어 , 내장 Input 클래스를 확장하고자 한다면 application/core/MY_Input.php,파일을 만들고 ,다음과같이 클래스를 선언합니다.:

    class MY_Input extends CI_Input {

    }

    Note:만약 생성자를 사용해야한다면 클래스 생성자에서 부모클래스의 생성자를 호출해주어야한다는점을 잊지마세요 :

    class MY_Input extends CI_Input {

        function __construct()
        {
            parent::__construct();
        }
    }

    Tip:  당신이 만든클래스내의 함주중에서 부모클래스(여기서는 내장클래스)의 이름과 같은 함수는 부모클래스의 함수 대신 사용됩니다.(메소드 오버라이딩과 같습니다). 이러한 특징으로 부분적인 내장 클래스 함수의 변경이 가능한것입니다..

    만약 컨트롤러 코어클래스(Controller core class)를 확장한다면, 컨트롤러 기반클래스를사용하는 당신의 프로그램에서 그부분을 확장된 기반클래스 이름으로 바꾸셔야합니다..

    class Welcome extends MY_Controller {

        function __construct()
        {
            parent::__construct();
        }

        function index()
        {
            $this->load->view('welcome_message');
        }
    }

    나만의 클래스에서 쓰는 접두어 바꾸기(Setting Your Own Prefix)

    접두어를 원하는대로 바꾸려면 application/config/config.php 파일을 여신후 아래의 변수를 찾습니다.:

    $config['subclass_prefix'] = 'MY_';

    모든 CodeIgniter 내장클래스는 접두어로 CI_ 을 사용하고 있으므로 여러분의 접두어에는 사용하시면 안됩니다.

    Security : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    보안Security

    본 페이지에서는 웹 보안에 대한 실용적기법들(best practices) 과 CodeIgniter 의 보안 항목에 관한 상세 설명을 제공합니다.

    URI 보안

    CodeIgniter 는 악의있는 데이터가 프로그램으로 전달되는것을 방지하기 위하여 URI 에 쓰는 문자를 상당히 제한하기 있습니다.URL 은 아래 사항들만 포함해야 합니다:

    Register_globals

    시스템 초기화과정에서 모든 글로벌 변수(global variables)들은 해제( unset ) 됩니다 .단 , $_GET,$_POST 및 $_COOKIE 배열은 예외입니다.해제 루틴은 register_globals = off 와 동일한 동작을 합니다.

    오류보고

    실제 서비스에서는 PHP의 에러표시기능을 꺼두는것이 좋습니다(internal error_reporting 플레그를 0 으로). 그렇게 하므로써 민감한 정보가 포함될 수있는 PHP 에러가 사용자에게 보이지 않도록 합니다.

    index.php에 포함된 CodeIgniter 상수 ENVIRONMENT 값을 ' production '으로 설정하면 오류메세지는 표시되지않습니다.개발 모드에서는 ' development '를 사용하는 것을 추천합니다 .환경별 처리 에서 환경별로 달리 처리할 수 있는 사항들을 확인하세요.

    magic_quotes_runtime

    magic_quotes_runtime지시자는 시스템 초기화과정에서 off 되므로 데이터베이스에서 데이터를 조회할때 슬래쉬를 제거할 필요가 없습니다..

    실용적 기법들 Best Practices

    서버로 부터 전달된데이터(사용자가 입력한 POST 데이터, COOKIE 데이터, URI 데이터, XML-RPC 데이터, SERVER 배열에 있는데이터 등)들을 처리하기전에 아래의 3단계를 거치는것이 좋습니다.

     

    1. 오염된 데이터를 필터합니다
    2. 올바른 타입,크기,길이 등의 사항들을 검증합니다. (이 단계가 1번단계를 대신할때도 있습니다.)
    3. 데이터베이스에 입력하기 전에 이스케이프(Escape) 합니다.

    CodeIgniter 는 이러한 단계를 지원하기 위하여 다음 함수들을 지원합니다:

    Hooks : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    후킹-프레임워크 코어확장 Hooks - Extending the Framework Core

    CodeIgniter의 후킹기능은 코어파일들을 해킹하지 않고도 내부작동방식을 변경할 수 있도록 합니다. CodeIgniter가 작동하기 시작하면 동작개념도에 설명된 처리순서에 따라서 일을 처리합니다. 그러나, 당신은 특정한 순서에서 처리하는 방식을 새롭게 바꾸고 싶을수도 있습니다. 예를들어, 당신은 컨트롤러가 로드되기전에 특정한 기능이 수행되도록 하고싶거나, 혹은 특정순서중에 당신만의 기능이 수행되도록 하고싶을 수도 있습니다.

    후킹 활성화 (Enabling Hooks)

    후킹은 글로벌로 동작하며 application/config/config.php 파일에 있는 아래변수를 통해서 활성화 가능합니다.:

    $config['enable_hooks'] = TRUE;

    후크 정의 (Defining a Hook)

    후크는 application/config/hooks.php 파일에 정의되어있습니다.각후크는 아래의 형태로 정의됩니다:

    $hook['pre_controller'] = array(
                                    'class'    => 'MyClass',
                                    'function' => 'Myfunction',
                                    'filename' => 'Myclass.php',
                                    'filepath' => 'hooks',
                                    'params'   => array('beer', 'wine', 'snacks')
                                    );

    주의:배열의 인덱스는 여러분이 사용하고자하는 후크포인트의 이름과 연관됩니다. 위 예제의경우에 후크포인트는 pre_controller 가 됩니다. 후크포인트의 목록은 아래에 있습니다. 다음 아이템들은 당신의 연관후크배열에 반드시 정의되어야 합니다.

    동일한 후크포인트에서 여러 후크 호출하기 Multiple Calls to the Same Hook

    같은 후크포인트를 하나이상의 스크립트에서 사용하고싶다면 간단히 배열정의를 다차원으로 합니다.

    예제:

    $hook['pre_controller'][] = array(
                                    'class'    => 'MyClass',
                                    'function' => 'Myfunction',
                                    'filename' => 'Myclass.php',
                                    'filepath' => 'hooks',
                                    'params'   => array('beer', 'wine', 'snacks')
                                    );

    $hook['pre_controller'][] = array(
                                    'class'    => 'MyOtherClass',
                                    'function' => 'MyOtherfunction',
                                    'filename' => 'Myotherclass.php',
                                    'filepath' => 'hooks',
                                    'params'   => array('red', 'yellow', 'blue')
                                    );

    주의할것은 대괄호([])가 각 배열 인덱스뒤에 있다는점입니다.:

    $hook['pre_controller'][]

    이것을 이용하면 다양한 스크립트를 같은 후크포인트로 사용할 수 있습니다. 배열의 순서는 처리순서가 될것입니다.

    후크포인트 Hook Points

    다음은 가능한 후크포인트 목록입니다..

    URI Routing : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    URI 라우팅 규칙 Routing

    일반적으로 URL 문자열과 클래스/함수 간에는 1대1 관계를 이룹니다

    URL 의 세그먼트는 통상 다음의 형태를 따릅니다:

    example.com/class/function/id/

    그러나 어떤 경우에는 위와같은 1대1 매칭 대신 다른 클래스 나 함수를 호출하고자 할때도 있을것입니다.

    예를들어 여러분은 아래와 같은 형식의 URL 을 원한다고 합시다:

    example.com/product/1/
    example.com/product/2/
    example.com/product/3/
    example.com/product/4/

    일반적으로 두번째 새그먼트는 함수이름이 되어야하나 , 위의 예에서는 함수이름대신 제품 ID 입니다.

    이렇게 하려면 CodeIgniter 의 재매핑(remap) 기능을 사용하시면 됩니다.

    나만의 라우팅 규칙 설정하기

    라우팅 규칙은 application/config/routes.php 파일에 정의되어있습니다.해당파일을 보시면 $route 배열이 있는데 그 배열을 통해 여러분만의 라우팅 규칙을 설정할 수 있습니다.라우팅은 와일드카드(*)정규표현식 으로도 설정할 수 있습니다.

    와일드 카드(*)

    일반적인 와일드 카드 라우팅은 아래와 같이 설정합니다:

    $route['product/:num'] = "catalog/product_lookup";

    라우팅 설정에서 배열의 키는 호출될 URI 를 나타내며, 배열의 값은 매핑될 도착지(실제로 사용자에게 보여질 URI)를 나타냅니다.

    위 예제에서 요청되는 URL 의 첫번째 새그먼트가 "product"이고 두번째 새그먼트가 숫자 가 됩니다. 이런 URL 요청이 들어오면 자동으로 catalog 클래스의 product_lookup 함수가 호출됩니다.

    라우팅에서 사용할수 있는 와일드 카드는 아래와같이 두가지(숫자,모든것)입니다.:

    (:num) 숫자로만 구성된 세그먼트와 일치합니다.
    (:any) 모든 문자와 일치합니다.

    Note: 라우팅 설정은 상위에 설정된것이 하위에 설정된것보다 우선실행됩니다.

    예제

    여기 몇몇 라우팅 예제가 있습니다:

    $route['journals'] = "blogs";

    URL 이 첫번째 새그먼트로 "journals" 을 가지고있다면 "blogs" 클래스로 재매핑 됩니다.

    $route['blog/joe'] = "blogs/users/34";

    URL 이 blog/joe 와같은 새그먼트를 포함하고 있다면 "blogs" 클래스의 "users" 함수로 재미핑되며 ID 값으로 "34" 가 설정됩니다.

    $route['product/(:any)'] = "catalog/product_lookup";

    URL 이 첫 새그먼트로 "product"를 포함하고 있고 두번째 세그먼트가 숫자라면"catalog" 클래스의 "product_lookup" 함수로 재매핑 됩니다.

    $route['product/(:num)'] = "catalog/product_lookup_by_id/$1";

    URL 이 첫 새그먼트로 "product" 를 포함하고 있고 두번째 세그먼트가 숫자라면"catalog" 클래스의"product_lookup_by_id" 함수로 연결되며 두번째 새그먼트는 변수로서 함수에 전달돌것입니다.

    Important: Do not use leading/trailing slashes.

    정규표현식

    라우팅 규칙을 설정하는데 정규표현식을 사용하고싶다면 가능합니다

    어떤 정규표현식도 후위참조(back-references)로서 사용가능합니다

    Note:  후위참조(back-references)를 사용하실때는 이중 백슬래쉬(\\)대신 달러($)를 사용해야합니다..

    정규표현식 경로설정은 일반적으로 다음의 형태를 가집니다:

    $route['products/([a-z]+)/(\d+)'] = "$1/id_$2";

    위 예제에서는, products/shirts/123 같은 경로가 shirts 컨트롤러의 id_123 함수로 매핑될 것입니다.

    또한,와일드 카드 및 정규표현식경로를 섞어 쓸수있습니다.

    예약된 라우팅 경로 (Reserved Routes)

    예약된 경로는 두가지가 있습니다:

    $route['default_controller'] = 'welcome';

    위 라우팅 경로는 URI 가 아무런 데이터도 포함하지않았을때 어떤 컨트롤러가 로드 될지 나타냅니다. 루트경로를 호출했을경우가 이에 해당합니다.

    위 예제의 경우 welcome 클래스가 로드될것입니다. 항상 기본 라우팅경로를 설정해둘것을 권장합니다. 그렇지않으면 404 에러페이지를 기본으로 내보낼테니까요.

    $route['404_override'] = '';

    이 라우팅 경로는 요청된 컨트롤러가 없으면 어떤 컨트롤러를 불러야 여부를 지정하는 것입니다. 이 설정은 기본 설정된 404 페이지를 덮어 씁니다. application/errors/error_404.php 의 기본 error_404.php 파일을 로드하는 show_404() 함수에는 영향을주지 않습니다.

     

    Important:  예약된경로는 어떤 와일드카드,정규표현식 경로보다 앞에 와야합니다..

    Managing your Applications : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    프로그램 관리법 Managing your Applications

    기본적으로 CodeIgniter 는 여러분이 단일 프로그램을 만들거나 관리하고 있으며 ,그것은application/ 폴더에 있다고 가정하고 있습니다. 그러나 하나의 CodeIgniter 아래 여러 프로그램을 관리하거나, application 폴더명을 변경하거나 이동 해야할때도 있을것입니다.

    Application 폴더 이름변경

    application 폴더의 이름을 변경하실수 있습니다. 만약 변경하신다면 메인 index.php 파일을 여신후$application_folder 변수를 변경하셔야 합니다.:

    $application_folder = "application";

    Application 위치 이동

    application 폴더의 위치를 system 폴더 아래가 아닌 다른곳으로 이동하실 수 있습니다.만약 이동하시면 메인 index.php 을 여신후 $application_folder 변수에 아래와 같이 전체 서버경로를 적어주세요:

    $application_folder = "/Path/to/your/application";

    하나의 CodeIgniter 로 여러 프로그램 관리(제작)하기

    하나의 CodeIgniter 로 여러 프로그램을 관리하시려면 각프로그램을 application 폴더아래 하위폴더로 두십시오. 각프로그램은 현재 application 폴더가 가지고 있는것처럼 config, controllers ..등등의 하위폴더구조를 그대로 유지해야합니다.

    예를 들어 "foo" 와 "bar" 이라는 두개의 프로그램을 관리한다고 하면. 폴더구조를 아래처럼하면 됩니다:

    applications/foo/
    applications/foo/config/
    applications/foo/controllers/
    applications/foo/errors/
    applications/foo/libraries/
    applications/foo/models/
    applications/foo/views/
    applications/bar/
    applications/bar/config/
    applications/bar/controllers/
    applications/bar/errors/
    applications/bar/libraries/
    applications/bar/models/
    applications/bar/views/

    특정 프로그램을 사용할때는 메인 index.php 파일을 연후$application_folder 변수에 그 경로를 입력합니다.

    예를들어,"foo" 프로그램을 사용하시려면 아래와 같이 설정합니다:

    $application_folder = "applications/foo";

    Note:  각 프로그램 해당프로그램 고유의index.php 파일이 필요합니다. 그 index.php 파일은 여러분이 원하시는 어떤 이름으로 하셔도 무방합니다.

    Quick Reference Chart : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    Quick Reference Chart

    For a PDF version of this chart, click here.

    Using CodeIgniter Drivers : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    CodeIgniter 드라이버 사용하기

    드라이버는 특별한 형태의 라이브러리이며, 하나의 부모클래스를 가지고, 여러개의 자식클래스들을 가질 수 있습니다.자식 클래스는 부모클래스에 접근할 수 있으나, 같은 수준의 클래스(siblings)에는 접근할 수 없습니다.

    드라이버는 컨트롤러에서 라이브러리 호출할때 우아한 문법 사용할 수 있는 혜택을 제공하며, 별도의 클래스로 분리할 것을 요구합니다. (드라이버에 들어가야할 코드를 컨트롤러에 두지말고 별도의 드라이버 클래스를 만들어 사용하므로써, 컨트롤러의 코드가 간소화 되어 우아한 문법을 사용할 수 있다는 의미인듯합니다)

    드라이버는 system/libraries 폴더 안에 있으며, 각 드라이버의 폴더명은 부모클래스의 이름과 동일합니다. 폴더 안에는 drivers 라는 하위 폴더를두고 모든 자식 클래스 파일을 그 안에 넣습니다.

    드라이버를 사용하기 위해서는 다음의 초기화 메서드를 사용하여 컨트롤러에서 초기화합니다:

    $this->load->driver('class name');

    여기서 class namee 은 호출하려는 드라이버 클래스의 이름입니다. 예를 들어, "Some Parent"라는 드라이버를로드하려면 다음과 같이합니다:

    $this->load->driver('some_parent');

    해당 클래스의 메서드는 다음과 같이 호출합니다:

    $this->some_parent->some_method();

    자식클래스를 초기화 하지않고 ,부모클래스에서 직접 호출할 수 있습니다:

    $this->some_parent->child_one->some_method();
    $this->some_parent->child_two->another_method();

    직접 드라이버 만들기

    드라이버 만들기섹션을 참고 해 주세요.

    Auto-loading Resources : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    리소스 자동로딩 Auto-loading Resources

    CodeIgniter 는 라이브러리,헬퍼,모델을 프로그램이 작동할때 자동으로 로드하는 기능을 지원합니다. 만약 특정리소스가 전체 프로그램에서 작동해야한다면, 자동 로드 기능을 사용하시는것이 편리합니다..

    다음의 리소스들이 자동으로 로드 가능합니다.:

    리소스를 자동으로 로드하기 위해서는 application/config/autoload.php 파일을 연다음autoload 배열에 추가하시면됩니다. 각 리소스의 사용자가이드에서도 자동로드 방법을 설명해 두었습니다..

    Note: 파일확장자(.php)를 자동로드 배열에 같이 쓰시면 안됩니다.

    Using CodeIgniter Libraries : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    CI 라이브러리 사용하기 Using CodeIgniter Libraries

    모든 라이브러리는 system/libraries 폴더에 있습니다. 대부분의 경우 ,라이브러리를사용하려면 컨트롤러 의 생성자에서 아래와같이 초기화해야합니다.:

    $this->load->library('class name');

    class name 은 호출하고싶은 클래스의 이름입니다.

    예를 들면,Form validation 클래스를 로드하려면 아래와같이 합니다:

    $this->load->library('form_validation');

    한번 초기화하면 사용자가이드에서 해당 클래스의 사용법을 참고하여 사용하시면됩니다.

    한번에 여러 라이브러리를 로드하려면, 배열을 파라미터로 넘기면 됩니다.

    $this->load->library(array('email', 'table'));

    나만의 라이브러리 만들기

    나만의 라이브러리 만들기 섹션을 참고하세요.

    Common Functions : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    일반 함수들Common Functions

    CodeIgniter 는 약간의 글로벌 함수를 지정해 두었으며, 여러분은 어떤곳에서도 그 함수들을 사용할 수 있습니다. 그 함수들은 별도의 라이브러리나 헬퍼의 로드과정이 필요없습니다.

    is_really_writable('path/to/file')

    is_writable() 함수는 윈도우 서버에서 해당파일이 읽기전용일때도 TRUE 를 반환합니다.그에 반해 본 함수는 실재로 파일을 작성해봐서 파일을 쓸수있는지를 확인합니다. OS 가 제공하는 쓰기가능 여부 정보를 신뢰할수 없을때만 사용하세요 .

    if (is_really_writable('file.txt'))
    {
        echo "I could write to this if I wanted to";
    }
    else
    {
        echo "File is not writable";
    }

    config_item('item_key')

    환경설정은 환경설정 라이브러리 를 사용하시는것이 좋습니다. 그러나 config_item() 함수를 이용해서도 단일 키를 가져올수 있습니다. 환경설정 라이브러리 페이지를 보시면 더 자세한 정보가 있습니다.

    show_error('message'), show_404('page'), log_message('level', 'message')

    이 함수들은 에러 핸들링 페이지를 참고하세요.

    set_status_header(code, 'text');

    서버의 status header를 직접 설정할때 씁니다. 예:

    set_status_header(401);
    // 헤더를: Unauthorized
    로 설정합니다

    요기에서 헤더에 사용할 수 있는 설정목록을 확인 하세요.

    remove_invisible_characters($str)

    ascii 문자 사이에 null문자가 들어가는것을 방지합니다.예:Java\0script.

    html_escape($mixed)

    htmlspecialchars() 함수의 단축버전입니다. 문자열이나 배열을 넘겨줄 수 있습니다. 크로스 사이트 스크립팅(XSS) 방어에 유용합니다.

    Views : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    뷰Views

    간단히 말하면 는 웹페이지이거나 헤더 푸터같은 웹페이지 조각입니다. 사실,뷰는 유연하게 다른 뷰에 삽입될수 있습니다.

    뷰는 절대로 직접 호출되지않고 ,컨트롤러를 통해서 호출됩니다. MVC 패턴에서 컨트롤러는 교통경찰같은 역할을 하며 어떤 뷰가 보여져야할지를 결정하는 책임 있다는것을 명심하세요 .만약 컨트롤러 페이지를 아직 읽지않으셨으면 반드시 먼저 읽어주세요 .

    컨트롤러 페이지에서 작성한 컨트롤러에 뷰를 추가해봅시다.

    뷰 만들기

    blogview.php 라는 파일을 만든후 아래의 코드를 입력하세요.:

    그리고 application/views/ 폴더안에 저장하세요.

    뷰 로딩하기

    특정 뷰 파일을 로드하기위해서 아래와 같은 코드를 사용합니다:

    $this->load->view('name');

    name 은 뷰 파일의 이름을 넣어주시면 됩니다. Note: .php 확장자는 넣지 마세요.

    이전에 만들었던 blog.php 컨트롤러를 여신후 echo 문장대신 View를 로드하도록 합니다:

    아래처럼 url 로 접속해 보면 echo 문으로 찍은 글 대신 새로 작성한 뷰를 보실수 있습니다:

    example.com/index.php/blog/

    여러개의 뷰를 로드하기

    CodeIgniter 는 컨트롤러에서 뷰를 로드($this->load->view)할때 지능적으로 동작합니다 from within a controller. 만약 2개이상을 로드하면 하나씩 덧붙여서(append) 출력합니다.예를들어 header view, a menu view, a content view, and a footer view 를 출력하고싶다면 아래와 같이 로드하시면 됩니다:

    <?php

    class Page extends CI_Controller {

       function index()
       {
          $data['page_title'] = 'Your title';
          $this->load->view('header');
          $this->load->view('menu');
          $this->load->view('content', $data);
          $this->load->view('footer');
       }

    }
    ?>

    위 예제같은 경우 우리는 아래에 소개하는 동적데이터추가 라는 방법을 쓸것입니다..

    뷰를 하위폴더에 저장하기

    뷰는 서브폴더에 저장될수 있습니다..이럴경우 뷰를 로드할때 폴더이름을 같이 적어주시면됩니다.

    예제:

    $this->load->view('folder_name/file_name');

    뷰에 동적으로 데이터 추가하기

    뷰를 로드할때 배열이나 객체를 두번째 파라미터로 전달할 수 있습니다.

    배열을 사용하는 예제:

    $data = array(
                   'title' => 'My Title',
                   'heading' => 'My Heading',
                   'message' => 'My Message'
              );

    $this->load->view('blogview', $data);

    객체를 사용하는 예제:

    $data = new Someclass();
    $this->load->view('blogview', $data);

    Note: 객체를 사용할때는 클래스의 변수가 배열의 요소로 변환됩니다.

    위에서만든 컨트롤러를 이용하여 한번 해봅시다:

    뷰 파일을 열어서 텍스트를 넘겨준 배열의 key이름과 같은 변수로 바꾸어봅시다.:

    그리고 URL로 접속해보면 변수값으로 바뀌어있는것을 확인할 수 있습니다.

    루프작성

    뷰에 넘겨주는 데이터는 단순한 변수로 제한되어있지 않습니다. 배열안의 값으로 다른 배열을 넣어서 전달할수 있으며, 넘겨받은 배열을가지고 루프를 이용하여 여러줄의 데이터를 표시할수 있습니다. 예를 들어 데이터베이스에서 데이터를 가져온다면 일반적으로 그 값을 다차원배열에 넣어 뷰로 전달하게 됩니다.

    다음 예제를 여러분의 컨트롤러에 추가하세요:

    그다음 뷰파일을 열어 루프를 작성합니다:

    Note: 위 예에서 우리가 PHP 대체문법을 이용하고 있다는걸 알수 있을것입니다. 이에대해 더 자세한 정보는여기 를 참조해주세요 .

    뷰를 데이터처럼 리턴받기(Returning views as data)

    세번째 파라미터(옵션) 를 사용하면 뷰를 브라우저로 전송하는대신 데이터로써 리턴하게됩니다. 뷰를 데이터로 처리해야할경우 유용하겠죠 . 아래와같이 3번째 파라미터를 true (boolean)로 설정하면 됩니다.기본값은 false 이며 이때 는 데이터를 브라우저로 전송하게 됩니다. 데이터로 리턴받을때는 변수에 할당해야한다는걸 잊지마세요 .:

    $string = $this->load->view('myfile', '', true);
    CodeIgniter URLs : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    CI 에서의 URL 규칙 CodeIgniter URLs

    CodeIgniter 에서 생성한 URL 은 깔끔하고 검색엔진에서 색인되기 좋은 구조입니다. 일반적인 쿼리스트링 기반의 URL 이 아니라 세그먼트 기반의 URL 을 사용합니다.

    example.com/news/article/my_article

    Note: 아래 기술된바와같이 쿼리스트링(Query string) URL 또한 사용할 수 있습니다(옵션).

    URI 세그먼트

    URL 세그먼트는 MVC패턴을 기반으로 아래와같이 표현됩니다. example.com/class/function/ID

    1. 첫세그먼트는 호출될 컨트롤러 class 를 나타냅니다.
    2. 두번째 세그먼트는 클래스안의 호출될 function, 혹은 메쏘드를 나타냅니다.
    3. 세번째 이후는 컨트롤러로 전달될 어떤 변수라도 될수 있습니다.(예제에서는 ID)

    URI 클래스URL 헬퍼 의 함수들을 이용하시면 손쉽게 URI 데이터를 조작하실 수 있습니다.그리고, URL 은 URI Routing 을 이용하시면 좀더 유연하게 재 매핑 될수 있습니다..

     

    index.php 파일 제거하기

    기본적으로 index.php 파일은 URL 에 아래와같이 포함됩니다:

    example.com/index.php/news/article/my_article

    .htaccess 파일을 규칙에 따라 사용하시면 쉽게 index.php 를 제거하실 수있습니다. 지정된것이 아니면 모두 리디렉션 하는 "negative" method(제한 메소드)를 아래와 같이 사용하세요:

    RewriteEngine on
    RewriteCond $1 !^(index\.php|images|robots\.txt)
    RewriteRule ^(.*)$ /index.php/$1 [L]

    위 예제의 설정을 통하여 index.php, images, robots.txt 를 제외한 HTTP 요청은 index.php 파일을 요청한 것으로 취급됩니다.

    URL 에 확장자 추가하기

    config/config.php 파일에서 URL 끝에 확장자를 추가하도록 설정할수 있습니다

    만약 URL 이 아래와 같다면:

    example.com/index.php/products/view/shoes

    .html 등의 확장자를 추가하여 일반적인 웹페이지인것 처럼 보이게 할수있습니다.:

    example.com/index.php/products/view/shoes.html

    쿼리스트링(Query Strings) 사용하기

    아래와같이 URL 에서 쿼리스트링을 사용하는게 필요한경우도 있을것입니다.:

    index.php?c=products&m=view&id=345

    application/config.php 파일에서 아래부분을 찾아보세요.

    $config['enable_query_strings'] = FALSE;
    $config['controller_trigger'] = 'c';
    $config['function_trigger'] = 'm';

    "enable_query_strings" 을 TRUE 로 바꾸면 됩니다. 이때 컨트롤러와 함수는 당신이 설정한 값에 따라서 호출할 수 있습니다(위의 경우 c 는 컨트롤러 호출 m 은 함수 호출):

    index.php?c=controller&m=method

    Please note: 쿼리스트링을 이용하시면 URL 헬퍼 ( form 헬퍼와 같이 URLs을 생성하는 헬퍼들) 을 사용하실수 없습니다.

    Creating Ancillary Classes : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    Creating Ancillary Classes

    In some cases you may want to develop classes that exist apart from your controllers but have the ability to utilize all of CodeIgniter's resources. This is easily possible as you'll see.

    get_instance()

    Any class that you instantiate within your controller functions can access CodeIgniter's native resources simply by using the get_instance() function. This function returns the main CodeIgniter object.

    Normally, to call any of the available CodeIgniter functions requires you to use the $this construct:

    $this->load->helper('url');
    $this->load->library('session');
    $this->config->item('base_url');
    etc.

    $this, however, only works within your controllers, your models, or your views. If you would like to use CodeIgniter's classes from within your own custom classes you can do so as follows:

    First, assign the CodeIgniter object to a variable:

    $CI =& get_instance();

    Once you've assigned the object to a variable, you'll use that variable instead of $this:

    $CI =& get_instance();

    $CI->load->helper('url');
    $CI->load->library('session');
    $CI->config->item('base_url');
    etc.

    Note: You'll notice that the above get_instance() function is being passed by reference:

    $CI =& get_instance();

    This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it.

    Creating Libraries : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    나만의 라이브러리 만들기Creating Libraries

    우리가 라이브러리(Libraries)라고 말할때는 일반적으로 libraries 폴더안에 위치하며 본 사용자 가이드에 설명되어있는 그것을 뜻합니다.하지만 여기서는 그 라이브러리가 아니라 님하가 어떻게 application/libraries 저장될 님하만의 라이브러리를 만들지를 설명합니다. 또한 그 라이브러리를 글로벌 라이버러리와 어떻게 분리하여 관리하는지도 설명합니다.

    보너스로 CodeIgniter 는 기존의 라이브러리를 확장하여 ( extend) 님하만의 라이브러리를 만들수 있도록 지원합니다.아니면 이미 내장된 라이브러리를 application/libraries 에 저장된 동일한 버전 및 이름의 님하가 만든라이브러리도 대체할수도 있습니다.

    요약하자면:

    아래에 설명된 내용들은 이러한 3가지를 어떻게 할수 있는지 상세하게 설명합니다..

    Note: 데이터베이스 클래스는 확장되거나 대체될 수 없습니다.그외 모든 클래스는 확장,대체될 수 있습니다.

    저장

    님하의 라이브러리는 반드시 application/libraries 에 위치해야합니다.CodeIgniter 가 초기화 과정에서 그 디렉토리를 살펴보기 때문입니다.

    이름짓기 관례(Naming Conventions)

    클래스 파일

    클래스는 반드시 아래의 프로토타입 형태를 따라야합니다.(Note: Someclass 이라는 이름은 예를 든것입니다.):

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Someclass {

        public function some_function()
        {
        }
    }

    /* End of file Someclass.php */

    여러분의 클래스를 사용하기

    어떤 여러분의 콘트롤러 함수에서도 여러분의 클래스를 아래와 같이 초기화 할수 있습니다.:

    $this->load->library('someclass');

    someclass 는 파일 이름이고 ".php" 확장자는 붙이지 않습니다..여기에서 파일이름을 대문자로 쓰든 소문자로 쓰든CodeIgniter 는 상관하지않고인식합니다..

    일단 로드되면 여러분의 클래스를 lower case 소문자 버전으로 사용해야합니다:

    $this->someclass->some_function();  // 객체는 항상 소문자로 사용되야합니다

    여러분의 클래스 초기화 과정에 파라미터 넘겨주기

    라이브러리 로드 함수에서 님하는 두번째 파라미터를 통하여 동적으로 데이터를 넘겨줄수 있습니다. 파라미터는 님하만의 클래스 생성자에 데이터를 넘겨줄것입니다.:

    $params = array('type' => 'large', 'color' => 'red');

    $this->load->library('Someclass', $params);

    이렇게 사용하려면 님하는 반드시 님하만의클래스 생성자에 파라미터를처리하는 코드를 삽입해야합니다.:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Someclass {

        public function __construct($params)
        {
            // Do something with $params
        }
    }

    ?>

    여러분의 config 파일에 저장된 데이터를 파라미터로 전달할 수 있습니다..간단히 클래스의 파일이름과 동일한 config 파일을 생성하여 application/config/ 폴더안에 저장하세요 .위에 기술된대로 동적으로 파라미터를 전달한다면 config 을 이용하는 방법은 비활성(will not be available)화 될것입니다.

    CodeIgniter 리소스를 여러분의 라이브러리와 함께 사용하기

    직접 만든 라이브러리에서 CodeIgniter에 내장된 리소스를 이용하려면 get_instance() 함수를 이용합니다. 그함수는 CodeIgniter 의 부모객체(super object)를 리턴합니다.

    일반적으로 당신이 만든 컨트롤러함수에서 $this 를 사용하여 CodeIgniter의 가능한 모든 함수들을 호출할것입니다.:

    $this->load->helper('url');
    $this->load->library('session');
    $this->config->item('base_url');
    etc.

    그러나  $this는 컨트롤러,뷰,모델에서만 직접적으로 사용할 수 있습니다.

    만약 당신이 만든 라이브러리(custom class) 에서 CodeIgniter의 클래스를 사용하고자한다면 아래와 같은 방법으로 해야합니다.:

    먼저 CodeIgniter객체를 변수로 할당합니다.:

    $CI =& get_instance();

    한번 할당한 후에는 $this 를 썼던 것대신에 새로할당한 변수($CI)를 대신 사용하면 됩니다:

    $CI =& get_instance();

    $CI->load->helper('url');
    $CI->load->library('session');
    $CI->config->item('base_url');
    etc.

    Note: 위에 사용된 get_instance() 는 객체를 참조로 넘겨줍니다.(& 를 주목할것):

    $CI =& get_instance();

    이것은 매우 중요합니다. 참조로 넘겨준다는것은 복사본이 아니라 원본의CodeIgniter 객체를 사용한다는것을 의미합니다.

    내장된 라이브러리를 나만의 라이브러리로 대체하기 Replacing Native Libraries with Your Versions

    간단히 당신의 라이브러리 이름을 내장된 라이브러리와 완전히 동일하게 하면 CodeIgniter 는 내장 라이브러리대신 당신의 라이브러리를 사용합니다. 이렇게 하려면 파일이름과 클래스 선언부를 내장라이브러리와 동일하게 하면 됩니다. 예를 들어, 내장 Email 라이브러리를 대체하려면 application/libraries/Email.php 파일을 만들고 클래스를 아래와 같이 선언합니다.

    class CI_Email {

    }

    주의 : 대부분의 내장라이브러리는 접두어CI_를 사용합니다.

    당신의 라이브러리를 로드 하라면 표준 로딩 함수를 사용하면 됩니다.:

    $this->load->library('email');

    Note: Database 클래스는 당신의 라이브러리로 대체될 수 없습니다..

    내장 라이브러리의 확장 Extending Native Libraries

    내장 라이브러리에 몇몇 기능요소들을 추가하려한다면(아마 한두개의 함수추가) 라이브러리 자체를 바꾸는것은 심한 오버헤드가 될것입니다. 이럴때는 간단히 내장라이브러리를 확장하는것이 현명합니다. 라이브러리확장은 몇가지를 제외하고는 라이브러리대체와 거의 비슷합니다.

    예를 들어 ,내장 Email 클래스를 확장하고자 한다면 application/libraries/MY_Email.php 파일을 생성하고 클래스를 아래와 같이 선언합니다:

    class MY_Email extends CI_Email {

    }

    Note: 만약 당신의 클래스에서 생성자를 사용하고자 한다면 부모클래스의 생성자를 그 내부에서 호출해야한다는걸 잊지마세요 :

    class MY_Email extends CI_Email {

        public function __construct()
        {
            parent::__construct();
        }
    }

    당신의 확장 클래스를 로드하는법 (Loading Your Sub-class)

    새롭게 만든 확장 클래스는 일반적인 클래스 로드와 동일한 방법으로 로드합니다.이때 접두어는 적으시면 안됩니다..예를들어 ,위의 예에서 만든 Email 클래스의 확장 클래스를 로드할때 아래와같이 합니다.:

    $this->load->library('email');

    한번 로드한 후에는 다른 일반적인 방법(확장하기전의 원본클래스를 사용하듯)과 동일하게 사용하면됩니다. 위에서 만든 Email 클래스의 경우 아래와 같이 사용합니다.:

    $this->email->some_function();

    나만의 접두어 설정 (Setting Your Own Prefix)

    나만의 접두어를 설정하려면 application/config/config.php 파일을 열어 아래 변수를찾으세요 :

    $config['subclass_prefix'] = 'MY_';

    주의 : 모든 CodeIgniter 내장 라이브러리는 접두어로 CI_ 를 사용하므로 위 설정에서는 CI_ 를 사용하지 마세요 .

    Controllers : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    컨트롤러 Controllers

    컨트롤러는 여러분 프로그램의 핵심이라 할수 있습니다. 왜냐하면 Http 요청을 어떻게 처리할지 결정하기 때문입니다.

     

    컨트롤러란 무엇인가?

    간단하게 말하면 컨트롤러는 URL과 상호작용하는 클래스 파일이라고 할수 있습니다.

    아래 URI를 보세요 :

    example.com/index.php/blog/

    위 예제에서 CodeIgniter 는 blog.php 라는 파일을 Controller 로서 찾은후 로드 합니다.

    컨트롤러의 이름이 URI 의 첫번째 새그먼트와 동일하다면 해당 컨트롤러는 자동적으로 로드될것입니다.

    따라해보세요:  Hello World!

    실재로 작동되는걸 확인해보는것이 쵝오죠 ! blog.php 라는 파일을 만든후 다음의 코드를 입력하세요 .

    그다음에 application/controllers/ 폴더에 저장하세요 .

    자 이제 아래예 처럼 브라우저에서 접속보세요 .(example.com 부분은 여러분의 url 로 대체되어야합니다):

    example.com/index.php/blog/

    정상적으로 하셨다면 Hello World! 라는 텍스트가 화면에 표시되는걸 보실수 있을거예요.

    Note: 클래스명은 반드시 대문자로 시작되어야합니다. 아래의 예제는 맞습니다.:

    <?php
    class Blog extends CI_Controller {

    }
    ?>

    그러나 아래의 예제는 틀렸습니다.

    <?php
    class blog extends CI_Controller {

    }
    ?>

    님하가 만드신 컨트롤러는 반드시 부모컨트롤러 로 부터 상속(extends)받아야합니다.그렇지않으면 컨트롤러의 기능을 사용할 수 없습니다.

    함수 (Functions)

    위 예제에서 함수이름은 index() 였습니다. "index" 함수는 URI 에서 두번째 새그먼트가 전달되지않을때 기본으로 실행됩니다. 아래와같은 방법으로도 위 예제와같이 "Hello World"를 화면에 뿌릴수 있습니다.

    example.com/index.php/blog/index/

    URI 의 두번째 새그먼트는 컨트롤러 내의 어떤함수가 실행될지를 결정합니다..

    따라해보세요. 새로운 함수를 컨트롤러에 추가합니다.

    아래 URL로 접속하여 comment 함수를 실행시켜봅시다:

    example.com/index.php/blog/comments/

    새로운 메세지가 보이시죠 ? 짝짝짝

    URI Segments 를 함수에 전달하기

    URI 가 2개보다 많은 세그먼트를 포함하고있다면 나머지들은 파라미터로 함수에 전달됩니다.

    예를들어 다음의 URL 이라면:

    example.com/index.php/products/shoes/sandals/123

    함수는 새그먼트 3번과 4번("sandals" 및 "123")을 파라미터로 전달받게 됩니다.

    <?php
    class Products extends CI_Controller {

        public function shoes($sandals, $id)
        {
            echo $sandals;
            echo $id;
        }
    }
    ?>

    중요:  만약 URI 라우팅(Routing) 을 사용하고있다면, 함수에전달된 새그먼트는 재 라우팅된 새그먼트 일것입니다.

    기본 Controller 정의

    새그먼트 없이 사이트의 루트 url 만 요청될때 실행될 기본 컨트롤러를 지정할 수 있습니다.

    기본 컨트롤러를 지정하려면application/config/routes.php 파일의 아래 변수에 세팅합니다.

    $route['default_controller'] = 'Blog';

    위와 같이 Blog를 기본 컨트롤러로 지정하면 루트 url 이 요청되었을때 이제는 Hello World를 보실수 있을것입니다.

    함수요청을 재 매핑 하기

    위에서 설명한것처럼, 일반적으로 URI 의 두번째 새그먼트는 컨트롤러내의 어떤 함수를 실행할것인가를 결정합니다. 이런 일반루틴을 재정의하여 원하는 액션으로 바꿀수 있습니다.그러려면_remap() 함수를 사용합니다.

    public function _remap()
    {
        // Some code here...
    }

    Important:  만약 컨트롤러가 _remap()함수를 포함하고이다면, URI가 어떻든간에 _remap() 함수를 호출하게될것입니다.왜냐하면 _remap()은 CI 가 정의해 놓은 일반루틴 대신 여러분 자신만의 라우팅방법으로 재정의 해버리기 때문입니다.

    재정의된 함수호출(일반적으로 URI의 두번째 새그먼트)은 함수명이 _remap() 의 파라미터로 전달됩니다:

    public function _remap($method)
    {
        if ($method == 'some_method')
        {
            $this->$method();
        }
        else
        {
            $this->default_method();
        }
    }

    _remap() 메서드로 넘기는 메서드이름 외의 파라미터는 모두 옵션입니다. 이 배열은 PHP의 call_user_func_array와 결합하여, CodeIgniter의 기본동작처럼 작동합니다.

    public function _remap($method, $params = array())
    {
        $method = 'process_'.$method;
        if (method_exists($this, $method))
        {
            return call_user_func_array(array($this, $method), $params);
        }
        show_404();
    }

    출력데이터 조절(Processing Output)

    CodeIgniter 는 최종적으로 렌더링되어 자동적으로 브라우저에 데이터를 전송해주는 출력클래스를 가지고있습니다. 뷰항목출력클래스 페이지에서 보다 자세한 정보를 보실수 있습니다. 그러나 어떤경우에는 최종적으로 데이터가 브라우저로 보내지기전에 뭔가 전처리를 해야할때도 있을것입니다. 그것은 컨트롤러에 _output() 함수를 추가하는 것으로 가능합니다.

    Important:  컨트롤러가_output()라는 함수를 가지고있다면 최종데이터를 바로 전송하는것 대신 그함수가 실행될것입니다.함수의 첫번째 파라미터는 최종출력데이터를 가지고있습니다.

    예제:

    public function _output($output)
    {
        echo $output;
    }

    중요 : _output() 는 최종데이터를 받습니다. 최종데이터가 _output()에 전달되기전에 벤치마크 및 메모리사용 데이터는 렌더링될것이고,캐시작성이 활성 상태라면 캐시파일도 작성되며, feature 항목을 사용한다면 헤더정보도 보내질것입니다.
    컨트롤러가 출력캐시를 정상적으로 보내게 하려면, _output() 메서드를 아래와 같이 사용하세요:
    if ($this->output->cache_expiration > 0)
    {
        $this->output->_write_cache($output);
    }

    그런데 이 함수를 사용한다면 페이지 실행시간 및 메모리사용상태정보는 정확하지 않을수 있습니다.왜냐하면 그러한 정보들은 당신이 _output() 에서 처리할 내용이 어떤것인지 계산에 넣고 있지 않기 때문입니다. 출력을 조절하는 다른방법은출력클래스 항목에서 찾아보세요.

    Private 함수

    때에따라서 함수의 공개적 접근을 허용해서는안될경우도 있을것입니다. 함수를private 으로 만들려면, 간단히 밑줄(_)을 함수이름앞에 추가해주세요.그러면 웹에서 호출할 수 없게 됩니다.

    예제:

    private function _utility()
    {
      // some code
    }

    아래와 같이 접근하려해도 작동하지않을것입니다:

    example.com/index.php/blog/_utility/

    컨트롤러들을 하위폴더로 구성하기

    대형 사이트를 만든다면 아마도 컨트롤러를 하위폴더로 구성하는것이 더 나을것입니다.

    application/controllers 아래에 폴더를 만든다음 컨트롤러 클래스들을 그안에 넣으세요.

    Note:  이런식으로 사용하는경우에 URI 첫번째 새그먼트는 반드시 폴더명이라야합니다.

    예를들어, 여러분의 컨트롤러 위치가 아래와같다면:

    application/controllers/products/shoes.php

    위의 컨트롤러를 호출하기위해서는 아래와같은 URI를 사용해야합니다:

    example.com/index.php/products/shoes/show/123

    각각의 하위폴더는 URL 에서 하위폴더만을 호출할때를 대비하여 기본 컨트롤러를 가지고 있어야 할것입니다. 간단히 기본컨트롤러를application/config/routes.php 파일에 설정하시면 됩니다.

    또한 CodeIgniter 는 URI 를URI라우팅( Routing) 기능을 이용하여 재 매핑할 수 있도록 지원하고있습니다.

    클래스 생성자

    컨트롤러에서 생성자를 사용하고자 한다면 생성자아래 반드시 아래의 코드가 들어있어야합니다.:

    parent::__construct();

    그렇지않으면 여러분이 만든 생성자가 부모 controller 의 생성자를 재정의 해버리기때문입니다.

    그러므로 반드시 위와같이 부모 controller 를 수동으로 호출해 주어야합니다.

     

    <?php
    class Blog extends CI_Controller {

           public function __construct()
           {
                parent::__construct();
                // 생성자 코드에 기능추가
           }
    }
    ?>

    생성자는 클래스가 초기화될때 어떤 기본값들을 설정해야한다거나 어떤 프로세스를 수행해야할때 유용합니다.생성자는 리턴값이 있어서는 안됩니다.

    예약된 함수명

    예약어 페이지를 참고해주세요

     

    Handling Multiple Environments : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    여러환경 처리

    개발자는 응용 프로그램 개발 환경 또는 프로덕션 환경에 따라 시스템이 다르게 동작하기를 원합니다. 예를 들어, 자세한 오류 출력은 개발중일때는 유용하지만, 실제 서비스에서는 보안 문제를 일으킬 수 있습니다.

    환경설정 상수

    기본적으로 CodeIgniter는 ENVIRONMENT상수가 ' development '로 설정되어 있습니다. index.php 맨 위에 다음과 같이 지정되어 있습니다:

    define('ENVIRONMENT', 'development');

    프레임 워크의 기본동작에 미치는 영향(아래섹션보시오) 이외에, 개발환경별 동작방식을 바꾸기위해 이 상수를 사용할 수 있습니다.

    프레임 워크의 기본동작에 미치는 영향

    CodeIgniter 시스템의 여러 장소에서 ENVIRONMENT 상수가 사용됩니다. 이 섹션에서는 기본 프레임 워크의 동작이 어떻게 영향을 받는지 설명합니다.

    오류보고

    ENVIRONMENT상수를 ' 'development' '로 설정하면 모든 PHP 오류가 발생할 때 브라우저에 표시됩니다. 반대로 ' production '으로 설정하면 오류를 표시하지 않습니다 . 프로덕션 환경에서 오류를 표시하지 않는것은 좋은 보안 관례 입니다.

     

    설정 파일

    필요하다면, CodeIgniter 가 특정 환경설정파일을 로드하도록 할 수 있습니다. 이것은 환경에 따라 다른 API 키를 사용 같은 경우 유용합니다. 자세한 내용은 설정 클래스 의 여러 환경 섹션에 설명되어 있습니다.

    Form Validation : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    폼 검증

    CodeIgniter는 포괄적인 폼 검증및 데이터 준비 클래스를 제공함으로써 작성하시는 코드의 양을 최소화 하도록 해 줍니다.

    주의:  CodeIgniter 1.7.0 이후 에서는 ,이전 버전의 폼검증 클래스와 달라졌습니다. 이전 버전의 클래스도 남겨두었기때문에 작동하는데는 문제가 없으나 새 폼검증 클래스를 사용하실것을 권장합니다.

     

    개요 Overview

    CodeIgniter 의 폼 검증 설명으로 들어가기전에 먼저 이상적인 시나리오를 만들어봅시다:

    1. 폼이 표시된다.
    2. 내용을 채우고 전송(submit)한다.
    3. 뭔가 적합하지않은것을 전송한다든지, 필수인항목을 빠뜨린다든지 했을경우 , 폼이 다시 표시되면서 관련 에러메세지를 뿌려준다.
    4. 정확하게 전송할때까지 이 과정을 반복한다.

    수신측에서의 스크립트는 반드시:

    1. 요구되는 데이터가 모두 들어왔는지 점검한다.
    2. 데이터의 형식이라든지 다른 요구되는 제한사항을 만족하는지 확인한다. 예를들어, 만약 사용자아이디(username)이 전송되었고 반드시 영문자만을 포함해야한다고 제한한다든지, 최소 최대길이를 지정한다든지, 이미 다른사람이 사용하고 있는아이디를 사용할수 없다든지,예약어를 사용할수 없다든지 등의경우가 있을수 있다.
    3. 보안을 위해서 데이터를 가공한다.
    4. 필요하다면 데이터를 전처리 한다(좌우공백제거나 html 인코딩 등)
    5. 데이터베이스 입력에 적합하도록 데이터를 준비한다.

    위 프로세스가 그리 복잡하지는 않지만, 일반적으로 대단히많은 소스코드가 필요하고 ,에러코드를 표시하기위해서 다양한 컨트롤 구조를 html 안에 코딩해야한다. 폼검증코드는 쉬운작업인 반면에 통상 그 양이 방대하고 지루한 작업이다.

     

    폼검증 튜토리얼 Form Validation Tutorial

    아래는 CodeIgniter 의 폼검증을 구현하기 위한 "수작업" 튜토리얼 입니다.

    폼검을 위해서는 아래 3가지 요소가 필요합니다:

    1. 폼을 포함한 파일.
    2. 전송이 성공했을때 "성공"메세지를 보여줄 파일.
    3. 전송된 데이터를 받아서 처리할 컨트롤러 함수.

    회원가입폼 예제를 통해서 이 세가지를 만들어 봅시다!

    폼 The Form

    텍스트 편집기를 이용하여 myform.php파일을 만듭니다. 그런다음 아래 코드를 삽입하고 applications/views/ 폴더에 저장합니다:

    성공 페이지 The Success Page

    텍스트 편집기를 이용하여formsuccess.php파일을 만듭니다. 그런다음 아래 코드를 삽입하고applications/views/ 폴더에 저장합니다:

    컨트롤러 The Controller

    텍스트 편집기를 이용하여form.php파일을 만듭니다. 그런다음 아래 코드를 삽입하고applications/controllers/폴더에 저장합니다:

    해봅세 ! Try it!

    브라우저에서 아래와 같은 URL 로 접속합니다(여러분의 환경에 맞는 url 입니다. 아래 그대로가 아니라 ..):

    example.com/index.php/form/

    폼을 전송(submit) 하면 단순히 폼이 리로드(reload) 되는것을 보실수 있습니다. 왜나하면 아직 검사(validation) 루틴을 작성하지 않았기 때문입니다.

    폼 검사 클래스에 어떤 검사코드도 넣지 않았기때문에 결과는 FALSE (boolean false) 를 기본값으로 리턴합니다.검사코드를 성공적으로 통과했을 경우에만 run() 함수는TRUE 를 리턴합니다.

    설명 Explanation

    위 페이지들로부터 여러가지를 아실수 있을거예요:

    (myform.php) 은 몇가지 예외들을 포함한 표준 웹폼(standard web form) 입니다:

    1. 폼은 폼을 여는 태그 대신 폼헬퍼(form helper) 를 사용합니다. 엄밀히말하면, 폼 헬퍼 사용은 꼭 필요하지 않을수 있습니다. 표준 html 을 이용하여 폼을 열수 있으니까요. 그러나, 폼헬퍼를 사용하면 설정(config)파일에 따라서 액션url(action URL)을 자동으로 생성해줍니다. 그렇게 되면 URL 이 변하더라도 쉽게 처리할 수 있겠지요.
    2. 폼의 맨위에 아래와 같은 함수호출이 있는것을 주목하세요 : <?php echo validation_errors(); ?>

      이 함수는 검사(validator)루틴으로 부터 되돌아오는 모든 에러메세지를 리턴합니다. 아무런 메세지가 없다면 빈문자열(empty string)을 리턴합니다.

    컨트롤러controller (form.php)는 index()라는 함수를 가지고 있습니다. 이함수는 뷰파일에서 사용할 검사클래스(validation class)를 초기화 하고 폼 헬퍼URL 헬퍼를 로드합니다. 또한 검사루틴을 실행(runs) 합니다. 검사루틴을 성공적으로 패스했는지 여부에 따라서 폼 자신이나 성공 페이지를 보여줍니다.

    검사루틴(규칙) 설정 Setting Validation Rules

    검사규칙은 원하는 만큼 제한없이 작성하실수 있으며 , 각 규칙들을 순서대로 처리하도록 할수 있습니다. 또한, 검사와 동시에 필드 데이터들을 전처리(pre-process)할수 있습니다. 검사규칙을 설정하기 위해서는set_rules() 함수를 사용합니다:

    $this->form_validation->set_rules();

    위 함수는 3가지 파라미터를 받습니다:

    1. 필드이름-폼에서 설정한 필드이름과 일치해야합니다.
    2. 위 필드이름에 대한 "사람이 알아보기 쉬운" 이름. 그 이름은 에러메세지에 삽입됩니다. 예를들어, 필드이름이"user" 라면 사람이 알아보기쉬운이름은 "Username" 정도로 하시면 됩니다. 부가설명: 필드이름을 랭귀지파일에 저장하고싶다면, 필드이름변환을 참조하세요.
    3. 폼에 필요한 검사규칙들.


    예제를 봐주세요. 컨트롤러 (form.php) 파일에 아래와같이 검사루틴을 초기화 시켜주세요:

    $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]');
    $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
    $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
    $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');

    컨트롤러는 아래와 비슷할것입니다:

    자 이제 필드를 공백으로둔 채 폼을 전송해봅시다. 에러메세지가 보여야 합니다. 만약 필드를 모두 채운상태에서 전송한다면 성공페이지가 보여야 합니다.

    주의: 지금까지로는 에러가 발생했을경우, 폼에 이미 입력한데이터는 다시 복원되지않습니다. 곧 복원되도록 만들어 봅시다ㅎㅎ.

    배열을 이용하여 검사규칙설정하기 Setting Rules Using an Array

    여러 검사규칙을 한번에 처리하는걸 좋아한다면, 배열을 사용하세요. 이 방법을 사용할때는 반드시 배열의 키이름을 아래와같이 해야합니다:

    $config = array(
                   array(
                         'field'   => 'username',
                         'label'   => 'Username',
                         'rules'   => 'required'
                      ),
                   array(
                         'field'   => 'password',
                         'label'   => 'Password',
                         'rules'   => 'required'
                      ),
                   array(
                         'field'   => 'passconf',
                         'label'   => 'Password Confirmation',
                         'rules'   => 'required'
                      ),   
                   array(
                         'field'   => 'email',
                         'label'   => 'Email',
                         'rules'   => 'required'
                      )
                );

    $this->form_validation->set_rules($config);

    규칙의 순차적 적용 Cascading Rules

    규칙을 여러개의 파이프라인처럼 연결해서 같이 적용할수 있습니다. 해볼까요. 아래와같이, 규칙설정함수의 세번째 파라미터를 아래와 같이 바꾸세요:

    $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
    $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
    $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
    $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

    위코드는 다음의 규칙을 설정합니다:

    1. Username 필드는 5 글자에서 12 글자 사이라야 한다.
    2. Password 필드는 패스워드 확인 필드와 일치해야한다.
    3. Email 필드는 유효한 email 주소라야 한다.

    해봅세! 적절하지 않은 데이터를 입력한후 폼을 전송하시면 여러분이 새로 설정한 규칙에 맞는 에러메시지를 뿌릴것입니다. 레퍼런스에는 사용가능한 다양한 규칙들이 있습니다.

    데이터 준비 Prepping Data

    위에서 사용해본 검사함수에 덧붙여, 여러분은 다양한 방법으로 데이터준비작업을 하실 수 있습니다.예를 들어, 아래와같이 규칙을 설정할 수 있습니다:

    $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|xss_clean');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|matches[passconf]|md5');
    $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required');
    $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');

    위 예제에서 , 필드의 좌우공백제거(trim), 암호를 MD5 로 변환, 부적합한 데이터를제거하기위해 username 에 "xss_clean" 함수적용시키기등을 수행했습니다.

    일반 PHP 함수중에 하나의 파라미터를 받는 함수라면 어떤것이라도 규칙처럼 사용할수 있습니다. 예를들어 htmlspecialchars, trim, MD5, 등입니다.

    참고: 일반적으로 검증규칙을 적용시킨후 데이터준비(prep)함수를 사용하게 됩니다. 이때 만약 에러가 발생한다면 원래데이터가 폼에 표시되게 됩니다.

    폼 데이터 복원하기 Re-populating the form

    지금까지는 에러관련부분 처리에 대해서 이야기해왔습니다.이제는 전송된 데이터를 다시 복원하는것에 대해서 이야기하겠습니다. CodeIgniter 에서는 그 작업을 위해서 여러가지 헬퍼함수를 제공합니다. 여러분이 가장 많이 사용할 함수는 아래함수입니다:

    set_value('field name')

    myform.php 뷰 파일을 연후 각 필드의value 부분을 set_value() 함수를 사용하여 업데이트합니다 :

    set_value() 함수의 파라미터로 필드이름을 넘겨줘야한다는것 잊지마세요!

    에러를 발생시키기 위해서 폼을 새로고침한후 전송하세요 . 이제 폼필드의 데이터들은 복원될것입니다.

    주의:아래의 함수참조 부분에서 <select> menus, radio button, checkbox 의 데이터를 복원하는 부분을 확인하세요.

    중요사항: 필드의 이름에 배열을 사용했다면 , 함수에도 배열형태 그대로를 넘겨줍니다.

    예:

    <input type="text" name="colors[]" value="<?php echo set_value('colors[]'); ?>" size="50" />

    더많은 정보는 아래의 필드이름으로 배열사용하기 에 있습니다.

    콜백(처리가 완료되면 자동으로 호출될함수지정)Callbacks: Your own Validation Functions

    검증시스템은 콜백을지원합니다. 이를 통해 검증클래스를 어려분의 필요에 따라 확장하는것이 가능합니다. 예를들어, 만약 사용자가 유일한 아이디를 선택했는지를 확인하기위해 데이터베이스 쿼리가 필요하다면, 그 기능을 위한 콜백함수를 만들수 있습니다.예제를 만들어 봅시다.

    컨트롤러에서, "username" 규칙을 아래와같이 바꿉니다:

    $this->form_validation->set_rules('username', 'Username', 'callback_username_check');

    그런후 컨트롤러에 username_check 라는 함수를 추가합니다. 그러면 컨트롤러는 아래예제와 비슷해질것입니다:

    폼을 새로고침한후 사용자명에 "test" 라고 입력하고 전송합니다. 필드데이터가 콜백함수에 전달되는것을 확인하실수 있습니다. 콜백함수에서 필요에따라 그 데이터를 처리하시면 되겠죠 .

    콜백을 호출하기위해서는 규칙에 있는 함수명을 "callback_" 라는 접두어와 함께 넣어주시면됩니다. 콜백함수에 추가 파라미터를 전달하고 싶다면, 콜백함수 뒤에 대괄호를 추가한후 그안에 넣어주시면 됩니다.예: "callback_foo[bar]" .

    여러분은 콜백으로 전달되는 폼 데이터를 처리하거나 리턴할수 있습니다. 콜백함수가 불린(boolean TRUE/FALSE) 외의 어떤 값을 리턴하더라도 원본의 폼데이터가 아니라 새롭게 처리된 데이터라고 가정합니다.

    에러메세지 설정 Setting Error Messages

    모든 내장 에러메세지는 아래의 언어파일에 있습니다 : language/english/form_validation_lang.php

    에러메세지를 설정하기위하여 위 파일을 수정하거나, 아래함수를 이용할 수 있습니다:

    $this->form_validation->set_message('rule', 'Error Message');

    규칙(rule)이름과 그 규칙과 관련하여 표시하고자하는 에러메세지(Error Message)를 넘겨주시면 됩니다.

    에러문자열에서 %s 를 사용하시면, 규칙을 설정할때 썼던 "사람이 알아보기쉬운이름" 으로 대체될것입니다.

    위 "callback" 예제에서 에러메세지는 함수이름을 넘겨주어 설정했습니다:

    $this->form_validation->set_message('username_check')

    언어파일(language file)에 있는 모든 에러메세지는 재정의될수 있습니다.예를들어 , "required" 규칙에 대한 메세지를 바꾸려면 아래와같이합니다 :

    $this->form_validation->set_message('required', 'Your custom message here');

    필드이름 변환 Translating Field Names

    set_rules() 함수에서 사용하였던 "사람이 알아보기 쉬운이름"을 언어파일에 저장하여 필드이름 변환이 적용되도록 하고싶다면 아래와 같이 합니다.:

    먼저, "사람이 알아보기쉬운이름(human) " 에 아래의 예제와 같이 lang:이라는 접두어를 붙입니다:

    $this->form_validation->set_rules('first_name', 'lang:first_name', 'required');

    그런다음, 그 이름을 언어파일의 배열에 저장합니다(접두어는 붙이지 않습니다):

    $lang['first_name'] = 'First Name';

    참고: 여러분의 언어파일에 저장된 배열 아이템은 CI 에서 자동으로 로드하지않습니다. 컨트롤러에서 아래와같이 로드하셔야 한다는것을 기억하세요:

    $this->lang->load('file_name');

    언어클래스(Language Class) 에 언어파일에 대해 더 자세한 정보가 있습니다.

    에러 구분자 바꾸기 Changing the Error Delimiters

    기본적으로 폼 검증 클래스는 에러메세지를 <p> 태그로 감쌉니다. 여러분은 이를 전역적으로 적용되도록 바꿀수도 있고 각각의 메세지에 적용되도록 바꿀수도 있습니다.

    1. 에러구분자를 전역적으로 바꾸기 Changing delimiters Globally

      컨트롤러에서 에러구분자를 전역적으로 바꾸는것은 폼검증 클래스를 로드 한후 아래와 같은 함수호출을 추가하시면 됩니다:

      $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

      이 예제에서는 div 태그를 사용하도록 바꾸었습니다.

    2. 각각의 에러에 적용되도록 구분자 바꾸기 Changing delimiters Individually

      아래 두개의 에러생성함수를 통해서 각각의 에러에 적용되는 구분자를 설정할수 있습니다:

      <?php echo form_error('field name', '<div class="error">', '</div>'); ?>

      Or:

      <?php echo validation_errors('<div class="error">', '</div>'); ?>

    에러를 각각 표시하기 Showing Errors Individually

    에러메세지를 목록처럼 표시하지않고 각 필드 옆에 표시하려면 form_error() 함수를 사용합니다.

    사용해보자구요! 폼을 아래와 같이 바꿉니다:

    에러가 없다면 아무것도 표시되지 않습니다.에러가 있다면 메세지가 표시되겠죠 .

    중요사항: 폼필드 이름으로 배열을 사용한다면, 함수 파라미터로 넘겨주는 이름도 배열 그대로라야 합니다. 예:

    <?php echo form_error('options[size]'); ?>
    <input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" />

    폼필드 이름으로 배열 사용하기 섹션에 더 자세한 정보가 있습니다.

     

    검사규칙셋을 설정파일에 저장하기 Saving Sets of Validation Rules to a Config File

    폼 검증클래스의 장점중 하나는 프로그램에 사용되는 모든 검증규칙을 하나의 설정파일에 저장할수 있다는점 입니다. 이런 규칙들을 그룹으로 묶을 수 있습니다. 이 그룹들은 필요할때 여러분이 직접 로드 할수도 있고 ,일치하는 controller/function 가 호출되었을때 자동으로 로드되게 할수도 있습니다.

    규칙들을 저장하는 방법 How to save your rules

    먼저 application/config/ 폴더 안에 form_validation.php 파일을 만듧니다.그리고 파일안에 $config 라는 이름의 배열을 만들어 규칙들을 집어넣습니다. 앞서 보여드린것과 같이 , 검증 배열은 아래와 같은 형태를 가집니다:

    $config = array(
                   array(
                         'field'   => 'username',
                         'label'   => 'Username',
                         'rules'   => 'required'
                      ),
                   array(
                         'field'   => 'password',
                         'label'   => 'Password',
                         'rules'   => 'required'
                      ),
                   array(
                         'field'   => 'passconf',
                         'label'   => 'Password Confirmation',
                         'rules'   => 'required'
                      ),   
                   array(
                         'field'   => 'email',
                         'label'   => 'Email',
                         'rules'   => 'required'
                      )
                );

    검증규칙파일은 run() 함수를 호출하면 자동으로 로드되어 적용됩니다.

    배열의 이름은 반드시 $config 라야 합니다.

    검증규칙 셋 작성 Creating Sets of Rules

    검증규칙을 모아서 하나의 셋으로 만들려면 그것들을 하나의 하위배열(sub arrays)로 만들어야합니다. 아래 예제는 두개의 규칙셋을 포함합니다. 하위배열이름인 "signup" 과 "email"은 임시로 대충붙인이름입니다. ㅎㅎ. 여러분은 여러분이 원하시는 다른 이름을 붙이시면되요 :

    $config = array(
                     'signup' => array(
                                        array(
                                                'field' => 'username',
                                                'label' => 'Username',
                                                'rules' => 'required'
                                             ),
                                        array(
                                                'field' => 'password',
                                                'label' => 'Password',
                                                'rules' => 'required'
                                             ),
                                        array(
                                                'field' => 'passconf',
                                                'label' => 'PasswordConfirmation',
                                                'rules' => 'required'
                                             ),
                                        array(
                                                'field' => 'email',
                                                'label' => 'Email',
                                                'rules' => 'required'
                                             )
                                        ),
                     'email' => array(
                                        array(
                                                'field' => 'emailaddress',
                                                'label' => 'EmailAddress',
                                                'rules' => 'required|valid_email'
                                             ),
                                        array(
                                                'field' => 'name',
                                                'label' => 'Name',
                                                'rules' => 'required|alpha'
                                             ),
                                        array(
                                                'field' => 'title',
                                                'label' => 'Title',
                                                'rules' => 'required'
                                             ),
                                        array(
                                                'field' => 'message',
                                                'label' => 'MessageBody',
                                                'rules' => 'required'
                                             )
                                        )                          
                   );

    특정 규칙 그룹 호출하기 Calling a Specific Rule Group

    특정규칙그룹을 호출하기위해서는 그룹이름을 run() 함수의 파라미터로 넘겨줍니다 . 예를 들어 ,signup 규칙그룹을 호출하려면 아래와같이 합니다:

    if ($this->form_validation->run('signup') == FALSE)
    {
       $this->load->view('myform');
    }
    else
    {
       $this->load->view('formsuccess');
    }

    컨트롤러 함수와 규칙그룹을 연관시키기 Associating a Controller Function with a Rule Group

    규칙그룹을 호출할때 좀더 자동화된 방법을 사용할수 있습니다. 컨트롤러의 class/function 이름 대로 규칙셋의 이름을 부여하시면 됩니다. 예를들어,컨트롤러 이름이 Member 이고 함수이름이 signup일때 컨트롤러 클래스는 아래와 같을것입니다:

    <?php

    class Member extends CI_Controller {

       function signup()
       {      
          $this->load->library('form_validation');
                
          if ($this->form_validation->run() == FALSE)
          {
             $this->load->view('myform');
          }
          else
          {
             $this->load->view('formsuccess');
          }
       }
    }
    ?>

    그러면 검사 설정파일에서는 , 규칙그룹을 member/signup라는 이름으로 만듭니다 :

    $config = array(
               'member/signup' = array(
                                        array(
                                                'field' => 'username',
                                                'label' => 'Username',
                                                'rules' => 'required'
                                             ),
                                        array(
                                                'field' => 'password',
                                                'label' => 'Password',
                                                'rules' => 'required'
                                             ),
                                        array(
                                                'field' => 'passconf',
                                                'label' => 'PasswordConfirmation',
                                                'rules' => 'required'
                                             ),
                                        array(
                                                'field' => 'email',
                                                'label' => 'Email',
                                                'rules' => 'required'
                                             )
                                        )
                   );

    규칙그룹이름이 클래스/함수 이름과 완전히 동일하다면 run() 함수만 호출해도 자동으로 적용됩니다.

     

    필드이름으로 배열 사용하기 Using Arrays as Field Names

    폼 검증 클래스는 필드명으로 배열을 사용할수 있도록 지원합니다. 다음예제를 보시죠:

    <input type="text" name="options[]" value="" size="50" />

    만약 필드이름으로 배열을 사용하신다면 , 필드명을 요구하는 헬퍼함수에 정확히 동일한 필드명을 전달해야합니다. 또한 검증규칙 필드명도 동일해야합니다.

    예를들어, 위 필드에대한 규칙을 설정한다면 아래와 같이 합니다:

    $this->form_validation->set_rules('options[]', 'Options', 'required');

    혹은 위 필드에 대한 에러메세지를 보여주기위해서는 다음과 같이합니다:

    <?php echo form_error('options[]'); ?>

    또한 데이터복원에 있어서는 다음과 같이 합니다:

    <input type="text" name="options[]" value="<?php echo set_value('options[]'); ?>" size="50" />

    필드이름으로 다차원 배열을 사용할수도 있습니다. 예:

    <input type="text" name="options[size]" value="" size="50" />

    혹은:

    <input type="text" name="sports[nba][basketball]" value="" size="50" />

    첫번째 예제에서보듯이 여러분은 반드시 헬퍼함수의 파라미터를 배열명과 정확히 일치하도록 해야합니다.:

    <?php echo form_error('sports[nba][basketball]'); ?>

    여러개의 옵션을 가진 체크박스를 사용한다면 각 옵션뒤의 대괄호[] 는 속이 비어있는채로 두셔야한다는것을 잊지마세요 .그래야만 선택한것들이 모두 POST 배열에 추가되게 됩니다.:

    <input type="checkbox" name="options[]" value="red" />
    <input type="checkbox" name="options[]" value="blue" />
    <input type="checkbox" name="options[]" value="green" />

    아래와 같이 다차원배열을 사용하실수도 있습니다:

    <input type="checkbox" name="options[color][]" value="red" />
    <input type="checkbox" name="options[color][]" value="blue" />
    <input type="checkbox" name="options[color][]" value="green" />

    헬퍼함수에서도 또한 빈 대괄호를 포함해야겠지요:

    <?php echo form_error('options[color][]'); ?>

     

    규칙 참조 Rule Reference

    다음은 CI에 내장된 규칙목록 입니다:

    규칙 파라미터 설명(여기서 문자라는것은 숫자,문자,기호등 모두 포함합니다) 예제
    required No 검사대상이 비어있으면 FALSE 를 리턴 합니다.  
    matches Yes 검사대상이 파라미터의 값과 일치하지않을때 FALSE 를 리턴 합니다 matches[form_item]
    is_unique Yes 파라미터에서 테이블 및 필드이름이 유일하지 않다면 FALSE 를 리턴합니다. is_unique[table.field]
    min_length Yes 검사대상의 길이가 파라미터 값보다 작을때 FALSE를 리턴 합니다 min_length[6]
    max_length Yes 검사대상의 길이가 파라미터 값보다 클때 FALSE를 리턴 합니다 . max_length[12]
    exact_length Yes 검사대상의 길이가 파라미터값과 다를때 FALSE를 리턴 합니다 . exact_length[8]
    greater_than Yes 검사대상이 지정된 값보다 작거나 숫자가 아닌 경우 FALSE를리턴 합니다. greater_than[8]
    less_than Yes 검사대상이 지정된 값보다 크거나 숫자가 아닌 경우 FALSE를리턴 합니다. less_than[8]
    alpha No 검사대상이 알파벳 이외의 문자를 포함할대 FALSE를 리턴 합니다.  
    alpha_numeric No 검사대상이 알파벳이나 숫자가 아닌 문자를 포함할때 FALSE를 리턴 합니다.  
    alpha_dash No 검사대상이 알파벳,숫자,밑줄(_),대쉬(-) 이외의 문자를 포함할때 FALSE를 리턴 합니다.  
    numeric No 검사대상이 숫자이외의 문자를포함할때 FALSE를 리턴 합니다.  
    integer No 검사대상이 정수이외의 문자를 포함할때 FALSE를 리턴 합니다.  
    decimal Yes 검사대상이 파라미터값과 일치하지 않으면 FALSE를 리턴 합니다.t  
    is_natural No 검사대상이 자연수 이외의 문자를 포함할때 FALSE를 리턴 합니다 ( 0, 1, 2, 3, 등 인지 검사).  
    is_natural_no_zero No 검사대상이 1 이상의 자연수 이외의 문자를 포함할때 FALSE를 리턴 합니다 (1, 2, 3, 등 인지 검사).  
    valid_email No 검사대상이 유효한 Email 주소가 아닐때 FALSE를 리턴 합니다 .  
    valid_emails No 검사대상이 콤마(,)로 구분된 Email 주소일 경우에 사용하며 유효한 email 주소가 아닐때 FALSE를 리턴 합니다.  
    valid_ip No 검사대상이 유효한 IP주소가 아닐때 FALSE를 리턴 합니다 .  
    valid_base64 No 검사대상이 Base64 에 사용되는 문자 이외의 문자를 포함할때 FALSE를 리턴 합니다 .  

    참고: 이 규칙들은 별도의 함수로서 호출할 수도 있습니다. 예제:

    $this->form_validation->required($string);

    참고: PHP 내장함수중 하나의 파라미터를 받는 함수라면 어떤 것도 여기서 사용할수 있습니다.

     

    데이터 준비 레퍼런스 Prepping Reference

    다음목록은 사용가능한 데이터준비함수들 입니다.:

    이름 파라미터 설명
    xss_clean No 입력클래스(Input Class) 페이지에 설명된 것처럼 데이터를 XSS 필터링 합니다.
    prep_for_form No 폼필드에 표시될수 있도록 특수문자를 변환합니다.
    prep_url No URL에 "http://"가 없으면 추가해 줍니다.
    strip_image_tags No 이미지 태그를 제거하고 이미지 url 을 추출합니다.
    encode_php_tags No PHP 태그를 HTML 엔터티로 변환합니다.

    참고: 하나의 파라미터만 받는 PHP 내장함수도 사용하실 수 있습니다 . trim, htmlspecialchars, urldecode, 등.

     

    함수 레퍼런스 Function Reference

    다음함수들은 컨트롤러에서 사용할 수 있습니다.

    $this->form_validation->set_rule();

    위에서 설명한대로 검사규칙들을 설정할수 있도록 해줍니다:

    $this->form_validation->run();

    검사루틴을 실행합니다. 성공하면TRUE 를 실패하면 FALSE를 리턴합니다. 필요할때는 검사규칙 그룹이름을 파라미터로 넘겨줄수 있습니다. 자세한 설명은 검사규칙을 그룹화하여 설정파일에 저장하기 를 참조해주세요 .

    $this->form_validation->set_message();

    여러분만의 에러메세지를 설정할수 있습니다.위의 에러메세지 설정(Setting Error Messages) 을 참고해 주세요.

     

    헬퍼 레퍼런스 Helper Reference

    아래 헬퍼 함수들은 폼을 포함하고 있는 뷰 파일에서 사용하실 수 있습니다. 이 함수들은 절차적 함수(객체아님)들 이기 때문에 $this->form_validation를 붙일 필요가 없습니다.

    form_error()

    함수로 넘겨진 필드명과 관련된 개별 에러메세지를 출력합니다. 예:

    <?php echo form_error('username'); ?>

    필요하다면 에러 구분자를 설정할수 있습니다.위의 에러구분자 변경(Changing the Error Delimiters) 섹션을 참고하세요.

    validation_errors()

    모든 에러메세지를 문자열로 출력합니다: 예:

    <?php echo validation_errors(); ?>

    필요하다면 에러 구분자를 설정할수 있습니다.위의 에러구분자 변경(Changing the Error Delimiters) 섹션을 참고하세요.

    set_value()

    input 이나 textarea 에 값을 설정합니다.이때 반드시 필드이름을 함수 첫번째 파라미터로 넘겨주어야 합니다. 필요하다면 두번째 파라미터로 기본값을 설정할 수 있습니다. 예:

    <input type="text" name="quantity" value="<?php echo set_value('quantity', '0'); ?>" size="50" />

    위 예제에서는 폼이 처음 로드될때 기본값이 "0" 이 설정되어 보여질 것입니다.

    set_select()

    <select> 를 사용할때 이 함수는 선택된 아이템을 표시하도록 해 줍니다.첫번째 파라미터는 반드시 select 의 name 을 포함해야 하며, 두번째 파라미터는 각 아이템의 값을 반드시 포함해야 합니다. 그리고 필요하다면 세번째 파라미터를 통해 특정 아이템을 기본값으로 지정할 수 있습니다(불린 TRUE/FALSE 를 사용합니다).

    예:

    <select name="myselect">
    <option value="one" <?php echo set_select('myselect', 'one', TRUE); ?> >One</option>
    <option value="two" <?php echo set_select('myselect', 'two'); ?> >Two</option>
    <option value="three" <?php echo set_select('myselect', 'three'); ?> >Three</option>
    </select>

    set_checkbox()

    체크박스를 전송될 당시의 상태로 보여지도록 합니다.첫번째 파라미터는 체크박스 이름을 포함해야하며, 두번째 파라미터는 그 값을 반드시 포함해야 합니다. 필요하다면 세번째 파라미터를 통해서 기본값을 설정할 수 있습니다.(불린 TRUE/FALSE 를 사용합니다)

    예:

    <input type="checkbox" name="mycheck[]" value="1" <?php echo set_checkbox('mycheck[]', '1'); ?> />
    <input type="checkbox" name="mycheck[]" value="2" <?php echo set_checkbox('mycheck[]', '2'); ?> />

    set_radio()

    라디오 버튼을전송될 당시의 상태로 보여지도록 합니다. 이 함수는 위 set_checkbox() 함수와 동일합니다.

    <input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> />
    <input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> />
    Calendaring Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    캘린더Calendaring Class

    캘린더 클래스를 이용하여 동적으로 캘린더를 만들 수 있습니다. 캘린더는 캘린더 템플릿을 통해서 형태가 결정되며 , 100% 커스터마이징이 가능합니다. 게다가, 켈린더 셀(cells)에 데이터를 전달하여 사용할 수 있습니다.

    클래스 초기화Initializing the Class

    CodeIgniter의 다른 대부분의 클래스들 처럼 캘린더 클래스또한 컨트롤러에서 초기화 하며,$this->load->library 함수를 사용합니다:

    $this->load->library('calendar');

    일단 로드된후에는 $this->calendar 코드로 캘린더 객체를 사용할 수 있습니다.

    캘린더 표시 (Displaying a Calendar)

    다음과 같은 코드를 이용하여 캘린더를 표시할 수 있습니다.:

    $this->load->library('calendar');

    echo $this->calendar->generate();

    서버 시간을 기준으로 한 캘린더 대신 특정 월의 캘린더를 만들고 싶다면 다음과같이 년,월을 캘린더 생성함수에 넘겨줍니다.:

    $this->load->library('calendar');

    echo $this->calendar->generate(2006, 6);

    위의 코드를 이용하면 2006년 6월의 캘린더가 생성됩니다..첫 파라미터는 년을 두번째파라미터는 월을 나타냅니다..

    캘린더 셀로 데이터 전달 (Passing Data to your Calendar Cells)

    캘린더 셀로 데이터를 전달하려면 아래의 예제처럼 연상배열을 만들어서 캘린더 생성함수의 세번째 파라미터로 넘겨줍니다. 연상배열의 키는 날짜를 나타내고, 값은 데이터를 나타냅니다.:

    $this->load->library('calendar');

    $data = array(
                   3  => 'http://example.com/news/article/2006/03/',
                   7  => 'http://example.com/news/article/2006/07/',
                   13 => 'http://example.com/news/article/2006/13/',
                   26 => 'http://example.com/news/article/2006/26/'
                 );

    echo $this->calendar->generate(2006, 6, $data);

    위 예제에서는 3, 7, 13, 26 일이 설정된 URL 을 카리키는 링크가 될것입니다.

    Note: 기본(default)적으로 당신이 만든 배열은 링크가 포함되어있다고 가정합니다.아래 템플릿 항목을 보시면 당신은 전달된데이터가 어떻게 사용되는지, 어떻게 커스터마이징할지, 어떻게 다른 타입의 정보를 전달해서 사용할지 알수 있을겁니다.

    표시 설정 (Setting Display Preferences)

    캘린더 표시 설정을 위해서 7가지 변수를 설정할 수 있습니다. 로드함수의두번째 파라미터로 설정배열을 넘겨주어 설정을 적용시킵니다.예제입니다:

    $prefs = array (
                   'start_day'    => 'saturday',
                   'month_type'   => 'long',
                   'day_type'     => 'short'
                 );

    $this->load->library('calendar', $prefs);

    echo $this->calendar->generate();

    위코드에서는 캘린더가 토요일부터 시작하며,긴(long)월 이름,짧은(short) 날짜이름을 사용하도록 세팅합니다.더 많은 정보는 아래테이블을 참조하세요

    Preference Default Value Options Description
    templateNoneNoneA string containing your calendar template. See the template section below.
    local_timetime()NoneA Unix timestamp corresponding to the current time.
    start_daysundayAny week day (sunday, monday, tuesday, etc.)Sets the day of the week the calendar should start on.
    month_typelonglong, shortDetermines what version of the month name to use in the header. long = January, short = Jan.
    day_typeabrlong, short, abrDetermines what version of the weekday names to use in the column headers. long = Sunday, short = Sun, abr = Su.
    show_next_prevFALSETRUE/FALSE (boolean)Determines whether to display links allowing you to toggle to next/previous months. See information on this feature below.
    next_prev_urlNoneA URLSets the basepath used in the next/previous calendar links.

    이전달,다음달 링크 만들기 Showing Next/Previous Month Links

    이전달 다음달 링크를 만들어 동적으로 달을 이동하도록하고싶다면 다음코드가 필요합니다.

    $prefs = array (
                   'show_next_prev'  => TRUE,
                   'next_prev_url'   => 'http://example.com/index.php/calendar/show/'
                 );

    $this->load->library('calendar', $prefs);

    echo $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));

    위코드를 통해서 몇몇가지를 알 수 있으실 겁니다.:

    캘린더 템플릿 만들기

    캘린더 템플릿을 통해서 디자인을 원하는 형태로 100% 수정 가능합니다.

    캘린더의 각 부분은 아래와같이 각각 한쌍의 축약코드변수(pseudo-variables) 안에 삽입됩니다.:

    $prefs['template'] = '

       {table_open}<table border="0" cellpadding="0" cellspacing="0">{/table_open}

       {heading_row_start}<tr>{/heading_row_start}

       {heading_previous_cell}<th><a href="{previous_url}">&lt;&lt;</a></th>{/heading_previous_cell}
       {heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
       {heading_next_cell}<th><a href="{next_url}">&gt;&gt;</a></th>{/heading_next_cell}

       {heading_row_end}</tr>{/heading_row_end}

       {week_row_start}<tr>{/week_row_start}
       {week_day_cell}<td>{week_day}</td>{/week_day_cell}
       {week_row_end}</tr>{/week_row_end}

       {cal_row_start}<tr>{/cal_row_start}
       {cal_cell_start}<td>{/cal_cell_start}

       {cal_cell_content}<a href="{content}">{day}</a>{/cal_cell_content}
       {cal_cell_content_today}<div class="highlight"><a href="{content}">{day}</a></div>{/cal_cell_content_today}

       {cal_cell_no_content}{day}{/cal_cell_no_content}
       {cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today}

       {cal_cell_blank}&nbsp;{/cal_cell_blank}

       {cal_cell_end}</td>{/cal_cell_end}
       {cal_row_end}</tr>{/cal_row_end}

       {table_close}</table>{/table_close}
    ';

    $this->load->library('calendar', $prefs);

    echo $this->calendar->generate();
    Typography Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    타이포그라피 Typography Class

    타이포그라피 클래스는 텍스트의 형태를 지정할수 있도록 해 줍니다(format text).

    클래스 초기화 Initializing the Class

    다른 모든 클래스들 처럼 , 타이포그라피 클래스도 $this->load->library 함수로 초기화 합니다:

    $this->load->library('typography');

    일단 로드되면, 타이포그라피 라이브러리 객체는 $this->typography 로 사용하실 수 있습니다.

    auto_typography()

    의미상,문자상의 텍스트 형태로 HTML을 변경합니다. 문자열을 입력받은후 아래의 형태들로 리턴합니다:

    사용예:

    $string = $this->typography->auto_typography($string);

    파라미터 Parameters

    옵션으로 사용하는 파라미터는 아래와 같이 두개가 있습니다.:

    1. Strip JavaScript Event Handlers. 보안을 위해서 모든 자바스크립트 핸들러를 벗길것인지를 결정합니다. TRUEFALSE를 사용합니다.
    2. Reduce Linebreaks. 2개이상의 줄바꿈을 2개로 줄일것인지 여부를 결정합니다. TRUEFALSE를 사용합니다.

    기본값으로, 파서는 자바스크립트 이벤트 핸들러는 벗기고, 줄바꿈 줄이기는 적용하지 않습니다. 다시말해, 파라미터를 적용하지 않으면 아래를 적용한것과 같이 동작합니다:

    $string = $this->typography->auto_typography($string, TRUE, FALSE);

    참고: 타이포그라피 포멧팅(Typographic formatting)은 처리해야할 양이 많은 경우 프로세서를 집중적으로 사용할 수도 있습니다(부하가 높아짐).만약 이 함수를 사용하고자 한다면, 페이지를 캐싱(caching) 하는것을 고려해보세요.

    convert_characters()

    이함수는 문자변환만을 수행한다는점을 제외하고는 위의 auto_typography 함수와 유사합니다:

    사용예:

    $string = $this->typography->convert_characters($string);

    nl2br_except_pre()

    <pre>안에 있는경우를 제외하면 줄바꿈을 <br />로 변경합니다. <pre>를 무시한다는점을 빼면 PHP내장함수인 nl2br() 함수와 동일합니다..

    사용예:

    $string = $this->typography->nl2br_except_pre($string);

    protect_braced_quotes

    타이포그라피 라이브러리를 템플릿파서 라이브러리와 함께 사용할때 , 괄호(curly brace)안의 따옴표(' 혹은 ")를 보호해야할 경우가 많이 생깁니다. 그럴경우 protect_braced_quotes 속성을 TRUE로 하세요

    사용예:

    $this->load->library('typography');
    $this->typography->protect_braced_quotes = TRUE;
    Email Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    이메일 Email Class

    CodeIgniter 의 이메일 클래스는 다음의 기능을 제공합니다:

    이메일 보내기

    이메일 보내기는 단순할뿐만아니라, 쉽게 설정을 추가할수 있고 , 원한다면 설정파일에 설정을 세팅할수도 있습니다.

    아래에 이메일 보내기 기본 예제이 있습니다.
    주의: 이 예제는 여러분이 컨트롤러에서 이메일을 보낸다는것을 가정합니다.

    $this->load->library('email');

    $this->email->from('your@example.com', 'Your Name');
    $this->email->to('someone@example.com');
    $this->email->cc('another@another-example.com');
    $this->email->bcc('them@their-example.com');

    $this->email->subject('Email Test');
    $this->email->message('Testing the email class.');

    $this->email->send();

    echo $this->email->print_debugger();

    이메일 환경설정 (Setting Email Preferences)

    환경설정 항목은 총 17가지 입니다.여기에서 설명하는것 처럼 여러분이 직접 설정할수도 있고 , 설정파일을 통해 자동으로 설정할수도 있습니다:

    환경설정을 하려면 먼저 설정내용을 배열로 만든후 , 이메일 초기화(initialize)함수로 전달하면 됩니다.아래에 예제가 있습니다:

    $config['protocol'] = 'sendmail';
    $config['mailpath'] = '/usr/sbin/sendmail';
    $config['charset'] = 'iso-8859-1';
    $config['wordwrap'] = TRUE;

    $this->email->initialize($config);

    정보: 대부분의 설정은 기본값을가지고 있기때문에 여러분이 설정값을 지정하지않으면 그 기본값으로 설정 됩니다..

    환경설정파일에 설정하기

    위와같이 직접 설정하지 않고 자동으로 설정되게 하려면, 환경설정파일에 설정값을 저장하세요 .먼저 email.php파일을 새로 만듧니다. 그리고 $config 배열을 그 파일에 추가합니다.마지막으로 config/email.php 로 저장합니다. 이렇게 하면 $this->email->initialize() 함수를 사용할 필요가 없습니다.

    이메일 환경설정 Email Preferences

    아래는 이메일 전송시 사용되는 설정 항목입니다.

    항목 기본값 옵션 설명
    useragentCodeIgniterNoneThe "user agent".
    protocolmailmail, sendmail, or smtp 메일전송 프로토콜(The mail sending protocol).
    mailpath/usr/sbin/sendmailNone Sendmail함수의 서버상 경로(The server path to Sendmail).리눅스(유닉스)에서 제공하는 sendmail을 말함
    smtp_hostNo DefaultNone SMTP서버주소(SMTP Server Address).
    smtp_userNo DefaultNone SMTP서버 사용자 아이디(SMTP Username).
    smtp_passNo DefaultNone SMTP서버 사용자 암호(SMTP Password).
    smtp_port25None SMTP서버 포트(SMTP Port).
    smtp_timeout5None SMTP서버 타임아웃(최대처리 혹은 대기)시간(초)(SMTP Timeout (in seconds)).
    wordwrapTRUETRUE or FALSE (boolean) 자동줄바꿈(Enable word-wrap).
    wrapchars76 자동줄바꿈시 한줄에 몇개의 문자를 허용할것인가를결정(Character count to wrap at).
    mailtypetexttext or html 메일 타입(일반텍스트/ html). 만약 html 형태의 메일을 보낸다면 삽입된 링크나 이미지 의 경로는 절대경로를 사용하세요 .그렇지않으면 여러분의 컴퓨터에서 잘보이던 페이지가 메일을 받은사람에게는 이것저것 깨져보일테니까요.
    charsetutf-8 문자셋(utf-8, iso-8859-1 등)(Character set (utf-8, iso-8859-1, etc.)).
    validateFALSETRUE or FALSE (boolean) 이메일주소가 적합한지 여부를 검사할지 말지 결정(Whether to validate the email address).
    priority31, 2, 3, 4, 5 이메일 우선순위1 =가장높음. 5 =가장낮음 . 3 = 중간.
    crlf \n "\r\n" or "\n" or "\r" 줄바꿈 문자 ( RFC 822 를 준수하기 위해 "\r\n"을 사용함 ).
    newline\n "\r\n" or "\n" or "\r" 줄바꿈 문자 ( RFC 822 를 준수하기 위해 "\r\n"을 사용함 )..
    bcc_batch_modeFALSETRUE or FALSE (boolean) BCC 배치모드 사용여부결정(Enable BCC Batch Mode).
    bcc_batch_size200None 각 BCC 배치에 몇개의 메일주소를 포함하도록할것인지결정(Number of emails in each BCC batch).

    이메일 함수 설명 Email Function Reference

    $this->email->from()

    메일 보내는 사람의 메일주소와 이름을 설정합니다:

    $this->email->from('you@example.com', 'Your Name');

    $this->email->reply_to()

    답신을 받을(reply-to) 메일 주소와 이름을 설정합니다. 설정하지않으면 from 함수에서 제공된 정보를 기본으로 사용하게 됩니다. 예제:

    $this->email->reply_to('you@example.com', 'Your Name');

    $this->email->to()

    수신자의 이메일주소를 설정합니다. 하나이상의 주소를 설정할수있으며 , 여러개를 설정할때는 콤마(,)로 구분하여 설정하거나, 배열로 넘겨줄수도 있습니다:

    $this->email->to('someone@example.com'); $this->email->to('one@example.com, two@example.com, three@example.com'); $list = array('one@example.com', 'two@example.com', 'three@example.com');

    $this->email->to($list);

    $this->email->cc()

    CC 메일주소를 설정합니다. "to" 함수처럼 , 하나이상의 주소를 설정할수있으며 , 여러개를 설정할때는 콤마(,)로 구분하여 설정하거나, 배열로 넘겨줄수도 있습니다

    $this->email->bcc()

    BCC 메일주소를 설정합니다. "to" 함수처럼 , 하나이상의 주소를 설정할수있으며 , 여러개를 설정할때는 콤마(,)로 구분하여 설정하거나, 배열로 넘겨줄수도 있습니다

    $this->email->subject()

    메일 제목을 설정합니다:

    $this->email->subject('This is my subject');

    $this->email->message()

    이메일 내용을 설정합니다:

    $this->email->message('This is my message');

    $this->email->set_alt_message()

    HTML 메일을 수신하지 못하는 수신자에게 전달하는경우에 html로 작성된 내용을 대신할 내용을 설정합니다:

    $this->email->set_alt_message('This is the alternative message');

    이 항목은 html로 내용을 작성할경우에 사용할 수 있는 옵션입니다. html 메세지를 보낼때 본 함수를 사용하여 대체메시지를 작성하시지않으면, CodeIgniter 는 자동으로 html 메세지에서 태그를 제거하여 대체메세지로 사용합니다.

    $this->email->clear()

    모든 이메일 변수들을 초기화 하여 비웁니다.이 함수는 루프를 이용하여 메일을 전송할 경우를 위하여 각 사이클 마다 데이터를 리셋하도록 해줍니다.

    foreach ($list as $name => $address)
    {
        $this->email->clear();

        $this->email->to($address);
        $this->email->from('your@example.com');
        $this->email->subject('Here is your info '.$name);
        $this->email->message('Hi '.$name.' Here is the info you requested.');
        $this->email->send();
    }

    파라미터로 TRUE 를 넘겨주면, 첨부파일도 함께 비워집니다:

    $this->email->clear(TRUE);

    $this->email->send()

    메일전송함수입니다. 전송성공여부에 따라서 TRUE / FALSE 를 반환합니다.아래와같이 전송성공여부를 체크하여 적절히 코딩하시면 되겠죠:

    if ( ! $this->email->send())
    {
        // Generate error
    }

    $this->email->attach()

    파일을 첨부할수 있게 해주는 함수입니다. 파일 경로와이름(path/name)을 첫번째 파라미터로 넘겨주세요.
    Note: URL이 아니라 파일경로를 넘겨야합니다. 여러개의 파일을 첨부할경우 함수를 여러번 호출해주시면됩니다.
    예제:

    $this->email->attach('/path/to/photo1.jpg');
    $this->email->attach('/path/to/photo2.jpg');
    $this->email->attach('/path/to/photo3.jpg');

    $this->email->send();

    $this->email->print_debugger()

    모든 서버메세지,이메일 헤더,이메일 메세지들을 포함한 문자열을 리턴합니다. 디버깅시에 유용함.

    자동줄바꿈 재정의 Overriding Word Wrapping

    자동줄바꿈을 사용할때, 아주 긴 링크를 포함한메세지의 경우 링크도 줄바꿈 되기때문에 클릭하면 바로 연결되지않는 상황이 발생할수있습니다. 이런경우 메세지의 일부분을 아래와같이 재정의하여 링크를 보호할 수 있습니다:

    The text of your email that
    gets wrapped normally.

    {unwrap}http://example.com/a_long_link_that_should_not_be_wrapped.html{/unwrap}

    More text that will be
    wrapped normally.

    {unwrap} {/unwrap}사이에 보호할 부분을 넣습니다

    Image Manipulation Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    이미지 Image Manipulation Class

    CodeIgniter의 이미지 처리 클래스 는 다음 기능을 제공합니다:

    3개의 주요 이미지 라이브러리는 다음 라이브러리가 필요합니다: GD/GD2, NetPBM, 그리고 ImageMagick

    주의: 워터마크는 GD/GD2 라이브러리가 사용가능해야 합니다. 그리고,다른 라이브러리들이 있더라도, 이미지 속성정보를 계산하기 위해 GD 는 기본으로 필요합니다. 그러나 이미지 처리는 여러분이 정의한 라이브러리를 가지고 수행할 수 있습니다.

    클래스 초기화 Initializing the Class

    다른 클래스들과 같이 ,이미지 클래스또한 $this->load->library 함수로 초기화 합니다:

    $this->load->library('image_lib');

    일단 초기화하면 바로 사용하실 수 있습니다. 이미지 라이브러리 객체는 다음과같이 사용합니다: $this->image_lib

    이미지 처리 Processing an Image

    이미지를 어떻게 처리하고자 하든지 (예를들어 크기조절,자르기,돌리기,워터마크),일반적인 사용법은 동일합니다. 어떤 처리를 할것인지에 따라서 약간의 속성을 설정한후 , 사용가능한 처리 함수를 호출하면 됩니다. 예를 들어, 썸네일을 만들고자한다면 아래와 같이 합니다:

    $config['image_library'] = 'gd2';
    $config['source_image'] = '/path/to/image/mypic.jpg';
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = TRUE;
    $config['width'] = 75;
    $config['height'] = 50;

    $this->load->library('image_lib', $config);

    $this->image_lib->resize();

    위 코드를 보면 image_resize 함수는 source_image 폴더에 있는 mypic.jpg 이미지를 찾은후 GD2 이미지 라이브러리 를 사용하여 75 X 50 사이즈의 썸네일을 생성합니다.maintain_ratio 옵션이 켜져 있으므로 ,썸네일은 원본의 가로세로 비율을 유지하면서 지정한 너비높이 에 최대한 가깝게 생성될것입니다.썸네일은 mypic_thumb.jpg 라는 이름으로 생성됩니다.

    주의: 이미지 처리가 정상적으로 진행되기 위해서는 이미지가 들어있는 폴더에 쓰기권한이 있어야 합니다.

    주의: 때에 따라서 이미지 처리가 서버메모리를 매우많이 사용할 수도 있습니다. out of memory 에러가 발생했다면, 메모리 최대크기를 제한하시기 바랍니다. PHP에서 사용할 수 있는 최대 메모리 설정도 같이 하시면 좋습니다.

    처리 함수들 Processing Functions

    처리함수는 4개가 있습니다:

    함수들은 처리성공시 TRUE 를 실패시 FALSE 를 리턴합니다. 만약 실패하면 아래 함수를 이용하여 에러메세지를 출력할 수 있습니다:

    echo $this->image_lib->display_errors();

    아래와 같이 조건문안에서 이미지를 처리하고 에러가 있을때만 에러메세지를 출력하도록 하면 좋습니다:

    if ( ! $this->image_lib->resize())
    {
        echo $this->image_lib->display_errors();
    }

    참고: 아래와같이 에러메세지의 시작부분과 끝부분에 원하는 html 코드를 추가하시면 보다 보기좋게 꾸밀수 있습니다:

    $this->image_lib->display_errors('<p>', '</p>');

    속성 Preferences

    아래 설명되어있는 속성들을통해서 이미지를원하는대로 재단 할수 있습니다.

    아래 속성들을 모든 이미지 처리함수에서 사용할수는 없습니다. 예를들어, x/y 축(axis) 속성은 이미지 자르기에서만 사용가능 합니다. 그리고, 너비(width) 와 높이(height) 속성은 자르기에서 아무런 소용이 없습니다. "지원함수(availability)" 칼럼에서 어떤 함수에 사용가능한지 표시해 줍니다..

    지원함수 범례 (Availability Legend):

    속성 기본값 옵션 설명 사용가능성
    image_library GD2 GD, GD2, ImageMagick, NetPBM 이미지 라이브러리를 사용가능하도록 세팅합니다. R, C, X, W
    library_path None None ImageMagick 이나 NetPBM 라이브러리의 서버경로(path)를 설정합니다. 둘중 어떤 라이브러리를 사용하더라도 , 경로를 설정해야합니다. R, C, X
    source_image None None 소스이미지의 경로/이름을 설정합니다. 경로는 URL이 아니라 절대경로나 혹은 상대경로로 설정합니다. R, C, S, W
    dynamic_output FALSE TRUE/FALSE (boolean) 이미지 파일이 동적으로 생성될지, 디스크에 저장될지를 결정합니다. 참고: 동적생성으로 설정할경우 한번에 하나의 이미지만 보여집니다 그리고, 페이지내에서 위치를 설정할 수 없습니다.단지 이미지 헤더와 함께 동적으로 브라우저에 출력됩니다. R, C, X, W
    quality 90% 1 - 100% 이미지의 품질을 설정합니다. 고품질일수록 파일의 크기는 커집니다. R, C, X, W
    new_image None None 이미지의 출력경로(destination)를 설정합니다. 이미지의 복사복을 생성할때 이 속성을 이용할수 있습니다. 경로는 URL이 아니라 절대경로나 혹은 상대경로로 설정합니다. R, C, X, W
    width None None 원하는 이미지의 너비를 설정합니다. R, C
    height None None 원하는 이미지의 높이를 설정합니다. R, C
    create_thumb FALSE TRUE/FALSE (boolean) 이미지 처리함수에 썸네일을 생성할것이라고 지정합니다. R
    thumb_marker _thumb None 썸네일지시자를 명시합니다.지시자는 파일 확장자 바로 앞에삽입됩니다. 예를들어 mypic.jpg 는 mypic_thumb.jpg 이 될것입니다 R
    maintain_ratio TRUE TRUE/FALSE (boolean) 원본이미지의 가로세로비율을 유지할지 혹은 입력된 수치대로 이미지 크기조절을 수행할지를 결정합니다. R, C
    master_dim auto auto, width, height 크기조절이나, 썸네일 생성시 어느축을 주축으로 할지를 정의합니다. 예를들어, 어떤 이미지를 100 X 75 로 리사이징 한다고할때, 이미지 원본의 비율이 이와달라서 완벽하게 처리될수 없다면 이 설정은 너비나 높이중 어느쪽을 중심으로 처리할것인지를 지정합니다. "auto" 는 이미지가 넓은 형태인지 높은 형태인지를 가지고 자동으로 주축을 결정합니다. R
    rotation_angle None 90, 180, 270, vrt, hor 이미지를 회전할때 몇도로 회전할지를 결정합니다. PHP 는 시계반대방향으로 회전시키므로 ,90도를 회전시키고자한다면 270 을 지정하셔야 합니다. X
    x_axis None None 이미지를 자를때 X 좌표를 픽셀단위로 설정합니다. 예를들어 , 30을 설정하면 왼쪽으로부터 30픽셀만큼 잘라냅니다. C
    y_axis None None 이미지를 자를때 Y 좌표를 픽셀단위로 설정합니다. 예를들어 , 30을 설정하면 위쪽으로부터 30픽셀만큼 잘라냅니다. C

    속성을 설정파일에 저장하기 Setting preferences in a config file

    속성을 위와같이 설정하는대신에 설정파일에 저장하고싶다면 image_lib.php라는 이름으로 새파일을 만드신후 $config 배열을 그안에 추가하시기 바랍니다. 그런다음 파일을 config/image_lib.php 로 저장하시면 자동으로 설정이 로드됩니다.설정파일에 저장하시면 $this->image_lib->initialize 함수를 호출할필요가 없습니다.

    $this->image_lib->resize()

    크기변경(resizing)함수를 이용하시면 크기변경,복사본생성(크기변경과 동시에 혹은 크기변경없이) 그리고 썸네일 생성 작업이 가능합니다..

    실재 썸네일마커를 썸네일파일이름에 추가하는것(예, mypic_thumb.jpg)을 제외한다면, 복사본생성과 썸네일 생성은 아무런 차이가 없습니다 .

    위에서 열거한 속성중 다음 세가지를 제외한 모든속성이 적용가능합니다: rotation_angle, x_axis, and y_axis.

    썸네일 생성 Creating a Thumbnail

    속성을 TRUE 로 설정하시면 크기변경함수는 썸네일파일을 생성하고 원본은 보존합니다:

    $config['create_thumb'] = TRUE;

    위 하나의 속성은 썸네일을 생성할지 말지를 결정합니다.

    복사본 생성 Creating a Copy

    아래의 속성에 복사본이 저장될 경로와 파일명을 지정해주시면 크기변환함수는 원본을 보존한채 복사본을 생성합니다:

    $config['new_image'] = '/path/to/new_image.jpg';

    이 속성에대한 참고사항:

    원본이미지의 크기변환 Resizing the Original Image

    위 두 속성중 아무것도 지정하지않으면 크기변환함수는 원본이미지를 변환합니다.

    $this->image_lib->crop()

    어느만큼 잘라낼지에대한 X,Y 값을 요구한다는점을 제외하면 자르기(cropping)함수는 크기변환 함수와 동일합니다.예제:

    $config['x_axis'] = '100';
    $config['y_axis'] = '40';

    윗쪽 테이블에 나열된 속성중 다음제외한 모든 속성이 사용가능합니다: rotation_angle, width, height, create_thumb, new_image.아래는 이미지를 잘라내는 예제입니다 :

    $config['image_library'] = 'imagemagick';
    $config['library_path'] = '/usr/X11R6/bin/';
    $config['source_image'] = '/path/to/image/mypic.jpg';
    $config['x_axis'] = '100';
    $config['y_axis'] = '60';

    $this->image_lib->initialize($config);

    if ( ! $this->image_lib->crop())
    {
        echo $this->image_lib->display_errors();
    }

    참고 : 비주얼한 UI가 없다면 이미지를 잘라내는것은 어렵습니다. 그러므로 비주얼한 UI를 제작하지 않는다면, 이함수는 그다지 유용하지 않습니다.우리는 우리가 개발한 CMS 프로그램인 ExpressionEngine에 사용된 포토갤러리에서 비주얼한 UI를 만들었습니다.자바스크립트를 이용해서 잘라낼 영역을 선택할수 있는 UI 를 말이죠 .

    $this->image_lib->rotate()

    이미지 회전 함수는 속성을 통해서 회전할 각도를 입력받습니다:

    $config['rotation_angle'] = '90';

    회전옵션은 5 가지가 있습니다:

    1. 90 - 반시계방향 90도.
    2. 180 - 반시계방향 180 도.
    3. 270 - r반시계방향 270 도.
    4. hor - 이미지를 가로로 대칭(flips)되도록 변환 .
    5. vrt - 이미지를 세로로 대칭(flips)되도록 변환 .

    아래는 이미지 회전에 대한 예제입니다:

    $config['image_library'] = 'netpbm';
    $config['library_path'] = '/usr/bin/';
    $config['source_image'] = '/path/to/image/mypic.jpg';
    $config['rotation_angle'] = 'hor';

    $this->image_lib->initialize($config);

    if ( ! $this->image_lib->rotate())
    {
        echo $this->image_lib->display_errors();
    }

    $this->image_lib->clear()

    clear 함수는 이미지처리에 쓰였던 모든값을 제거(clear)합니다. 이미지처리를 루프에서 한다면 이함수를 사용하게 될것입니다.

    $this->image_lib->clear();

     

    워터마크 Image Watermarking

    워터마크를 사용하려면 GD/GD2 라이브러리가 필요합니다.

    두개 타입의 워터마크 Two Types of Watermarking

    사용가능한 워터마크는 아래와같이 2개의 타입이 있습니다:

    이미지에 워터마크 하기 Watermarking an Image

    다른 함수들과 마찬가지로 (크기변환, 자르기, 회전) 워터마크도 필요한 속성을 설정하고 워터마크 함수를 호출하면 됩니다. 아래예제를 참고하세요:

    $config['source_image'] = '/path/to/image/mypic.jpg';
    $config['wm_text'] = 'Copyright 2006 - John Doe';
    $config['wm_type'] = 'text';
    $config['wm_font_path'] = './system/fonts/texb.ttf';
    $config['wm_font_size'] = '16';
    $config['wm_font_color'] = 'ffffff';
    $config['wm_vrt_alignment'] = 'bottom';
    $config['wm_hor_alignment'] = 'center';
    $config['wm_padding'] = '20';

    $this->image_lib->initialize($config);

    $this->image_lib->watermark();

    위 예제에서는 "Copyright 2006 - John Doe" 라는 글자를 가지고 16픽셀 트루타입폰트로 워터마크를 생성합니다. 워터마크는 이미지의 하단 가운데 위치하며, 바닥에서부터 20픽셀위치에 있게됩니다.

    참고: 이미지 클래스를 사용하기위해서는 이미지파일에 쓰기권한이 설정되어있어야 합니다. 예를들어 777 등으로 설정해주세요.

    워터마크 속성 Watermarking Preferences

    아래 테이블은 텍스트나 오버레이 워터마크에 사용할수 있는 속성을 보여줍니다.

    속성 기본값  옵션 설명
    wm_type text text, overlay 워터마크 타입을 설정합니다.
    source_image None None 소스이미지의 경로와 파일이름을 설정합니다.경로는 URL 이 아니라 절대경로나 상대경로로 설정해야합니다.
    dynamic_output FALSE TRUE/FALSE (boolean) 이미지 파일이 동적으로 생성될지, 디스크에 저장될지를 결정합니다. 참고: 동적생성으로 설정할경우 한번에 하나의 이미지만 보여집니다 그리고, 페이지내에서 위치를 설정할 수 없습니다.단지 이미지 헤더와 함께 동적으로 브라우저에 출력됩니다.
    quality 90% 1 - 100% 이미지의 품질을 설정합니다. 고품질일수록 파일의 크기는 커집니다.
    padding None A number 워터마크가 이미지의 경계로부터 기본적으로 얼마나 떨어질지에 대한 패딩(padding) 을 픽셀로 설정합니다. (html 테이블에서 padding 설정하는것과 같은개념).
    wm_vrt_alignment bottom top, middle, bottom 워터마크이미지의 세로 정렬을 설정합니다
    wm_hor_alignment center left, center, right 워터마크이미지의 가로 정렬을 설정합니다
    wm_hor_offset None None 워터마크 이미지의 가로 위치를 픽셀로 설정합니다. 통상 오프셋을 설정하면 워터마크는 설정값 만큼 오른쪽으로 이동하게 됩니다. 그러나 alignment를 right 로 설장하면 왼쪽으로 이동합니다.
    wm_vrt_offset None None 워터마크 이미지의 세로 위치를 픽셀로 설정합니다. 통상 오프셋을 설정하면 워터마크는 설정값 만큼 아래로 이동하게 됩니다. 그러나 alignment를 bottom으로 설장하면 위쪽으로 이동합니다.

    텍스트 속성 Text Preferences

    아래테이블은 워터마크가 텍스트 타입일때 사용할수 있는 속성입니다.

    속성 기본값 옵션 설명
    wm_text None None 워터마크로 사용할 텍스트를 설정합니다. 일반적으로는 저작권(copyright)관련 텍스트를 쓰겠지요.
    wm_font_path None None 사용할 트루타입폰트의 서버경로를 설정합니다.이 옵션을 설정하지 않으시면 GD에 내장된 폰트가 사용됩니다.
    wm_font_size 16 None 폰트크기입니다. 참고: 위의 트루타입 옵션을 사용하지 않으면, 숫자는1 - 5 까지 설정할수 있습니다. 그렇지않다면, 사용하는 폰트에 대해 가능한 크기를 모두 사용할수 있습니다(픽셀단위로 설정).
    wm_font_color ffffff None 폰트색상을 16진수로 설정합니다. 참고, 3글자의 축소버전(예 fff) 컬러설정대신 반드시 6 글자의 16진수값을 모두 사용해야합니다(예, 993300).
    wm_shadow_color None None 그림자의 색상을 16진수로 설정합니다. 이설정을 사용하지않으면 그림자는 생성되지 않습니다. 참고, 3글자의 축소버전(예 fff) 컬러설정대신 반드시 6 글자의 16진수값을 모두 사용해야합니다(예, 993300).
    wm_shadow_distance 3 None 그림자가 얼마나 떨어져서 표시될지를 픽셀단위로 지정합니다.

    오버레이 속성 Overlay Preferences

    아래테이블은 워터마크가 오버레이 타입일때 사용할수 있는 속성입니다.

    속성 기본값 옵션 설명
    wm_overlay_path None None 워터마크로 사용할 이미지의 서버경로를 설정합니다. 오버레이타입의 워터마크 생성시에만 필요합니다.
    wm_opacity 50 1 - 100 이미지 투명도를 설정합니다. 이 설정을 통해서 원본이미지위체 반투명으로 워터마크를 생성할수 있습니다. 일반적으로 50% 로 설정합니다.
    wm_x_transp 4 A number 워터마크 이미지로 PNG 혹은GIF를 사용한다면, 어떤 색깔을 투명으로할지 설정해야할 것입니다. 이 속성을 통해 설정할 수 있습니다.이 속성과 아래 속성을 함께 사용하여 좌표를 지정하면 왼쪽 위를 0으로 하여 지정한 픽셀만큼의 위치에 있는색깔과 같은 색깔을 투명으로 설정합니다.
    wm_y_transp 4 A number 위 설정과 함께 , 투명하게 할색상의 위치를 표현하는데 쓰입니다.
    Caching Driver : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    캐싱 드라이버

    CodeIgniter는 몇 가지 가장 인기있는 형식의 빠른 동적 캐싱에 대한 래퍼를 제공합니다. 파일 기반 캐싱 이외는 특​정한 서버 요구 사항이 필요합니다.만약 필요한 요구사항이 만족되지 않으면 치명적인 예외를 던집니다.

    목차

    사용 가능한 드라이버

    사용 예제

    The following example will load the cache driver, specify다음 예제는 APC 를 캐시드라이버로 로드하고, APC를 사용할 수없는 경우 파일 기반 캐싱으로 대체합니다.

    $this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));

    if ( ! $foo = $this->cache->get('foo'))
    {
         echo 'Saving to the cache!<br />';
         $foo = 'foobarbaz!';

         // Save into the cache for 5 minutes
         $this->cache->save('foo', $foo, 300);
    }

    echo $foo;

    함수 가이드

    is_supported(driver['string'])

    이 메서드는$this->cache->get()를 통해 드라이버에 접근할 때 자동으로 호출됩니다. 그러나, 만약 별도의 드라이버를 사용하는 경우이 메서드를 호출하여 드라이버가 서버환경에서 지원되는지 확인하십시오..

    if ($this->cache->apc->is_supported())
    {
         if ($data = $this->cache->apc->get('my_cache'))
         {
              // do things.
         }
    }

    get(id['string'])

    이 메서드는 캐시에서 한 항목을 가져옵니다. 만약 해당 항목이없는 경우,이 메소드는FALSE 을 반환합니다.

    $foo = $this->cache->get('my_cached_item');

    save(id['string'], data['mixed'], ttl['int'])

    캐시에 한 항목을 저장합니다. 저장에 실패하면FALSE를 리턴합니다.

    옵션인 세번째 파라미터(캐시 생존시간)의 기본값은 60 초 입니다.

    $this->cache->save('cache_item_id', 'data_to_cache');

    delete(id['string'])

    캐시에서 지정한 항목을 제거합니다.제거에 실패하면 FALSE를 리턴합니다.

    $this->cache->delete('cache_item_id');

    clean()

    모든 캐시를 지웁니다.지우는데 실패하면 FALSE를 리턴합니다..

    $this->cache->clean();

    cache_info()

    모든 캐시에 대한 정보를 리턴합니다.

    var_dump($this->cache->cache_info());

    get_metadata(id['string'])

    특정 캐시 항목에 대한 상세정보를 리턴합니다.

    var_dump($this->cache->get_metadata('my_cached_item'));

    드라이버

    Alternative PHP Cache (APC) 캐싱

    위에서 설명한 함수들은 아래와 같이 특정 어댑터를 지정하지 않고 사용할 수 있습니다.:

    $this->load->driver('cache');
    $this->cache->apc->save('foo', 'bar', 10);

    APC에 대한 더 자세한 정보는 http://php.net/apc 를 참조하십시오.

    파일기반 캐싱

    출력 클래스의 캐싱과 달리 파일 기반 캐싱 드라이버는 뷰파일의 일부를 캐시할 수 있습니다. 파일기반의 캐싱은 주의해서 사용해야 합니다. 디스크에 읽고 쓰는것이 너무 빈번해져 캐싱의 효과를 넘어서버릴 수 있습니다..

    위에서 설명한 모든 메서드는 다음과 같이 특정 어댑터를 드라이버 로더에 지정하지 않고 사용할 수 있습니다:

     

    $this->load->driver('cache');
    $this->cache->file->save('foo', 'bar', 10);

    메모리에 캐싱

    application/config/ 에 있는 memcached.php 설정파일에 여러개의 메모리캐싱서버를 지정할 수 있습니다.

    위에서 설명한 모든 메서드는 다음과 같이 특정 어댑터를 드라이버 로더에 지정하지 않고 사용할 수 있습니다::

    $this->load->driver('cache');
    $this->cache->memcached->save('foo', 'bar', 10);

    For more information on Memcached, please see http://php.net/memcached

    더미 캐시

    캐시의 끝단이며, 항상 'miss'합니다.(뭔소린지 ..).데이터를 저장하지는 않지만, 캐싱이 지원되지 않는 환경에서도 캐싱 소스코드를 유지할 수 있게 합니다.

    URI Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    URI Class

    URI 클래스는 URI 문자열로부터 원하는 정보를 추출할수 있도록 해주는 함수를 제공합니다. 만약 URI 라우팅을 사용하신다면, 재 라우팅(re-routed ) 세그먼트에 대한 정보도 추출할 수 있습니다.

    참고: 클래스는 시스템에의해 자동으로 로드되므로 직접 로드하실 필요가 없습니다.

    $this->uri->segment(n)

    특정 세그먼트를 추출해 냅니다. n 은 추출하고자하는 세그먼트의 번호입니다. 세그먼트번호는 왼쪽에서 오른쪽으로 매겨집니다. 예를들어 , URL 이 다음과 같다면:

    http://example.com/index.php/news/local/metro/crime_is_up

    세그먼트번호는 아래와 같습니다:

    1. news
    2. local
    3. metro
    4. crime_is_up

    기본값으로, 세그먼트가 존재하지않으면 FALSE 를 리턴합니다. 필요하다면, 두번째 파라미터로 세그먼트가 없을때 리턴될 기본값을 지정할수 있습니다. 예를들어 , 아래예제는 실패시에 숫자 0을 리턴하도록 합니다:

    $product_id = $this->uri->segment(3, 0);

    위 코드는 아래와같은 코드를 작성할 필요가 없도록 해줍니다:

    if ($this->uri->segment(3) === FALSE)
    {
        $product_id = 0;
    }
    else
    {
        $product_id = $this->uri->segment(3);
    }

    $this->uri->rsegment(n)

    이함수는 위의 함수와 동일합니다. 다만, CodeIgniter URI 라우팅을 사용하실때 최종적으로 재 라우팅(re-routed) 되는 URI 의 특정 세그먼트의 값을 추출한다는것만 다릅니다.

    $this->uri->slash_segment(n)

    이함수는 $this->uri->segment()와 거의 같습니다. 다만, 두번째 파라미터에의해 앞(leading),뒤(trailing) 혹은 양쪽(both)에 슬래시(/)를 추가한다는점만 다릅니다. 파라미터를 사용하지않으면 뒤쪽 슬래시가 붙습니다. 예:

    $this->uri->slash_segment(3);
    $this->uri->slash_segment(3, 'leading');
    $this->uri->slash_segment(3, 'both');

    결과:

    1. segment/
    2. /segment
    3. /segment/

    $this->uri->slash_rsegment(n)

    이함수는 위의 함수와 동일합니다. 다만, CodeIgniter URI 라우팅을 사용하실때 최종적으로 재 라우팅(re-routed) 되는 URI 의 특정 세그먼트에 슬래시(/)를 추가한다는점만 다릅니다.

    $this->uri->uri_to_assoc(n)

    이함수는 URI 세그먼트를 키/값 쌍으로된 연관배열로 리턴합니다.아래 URI를 보시죠:

    index.php/user/search/name/joe/location/UK/gender/male

    이함수를 사용하시면 아래와같은 형태의 연관배열을 얻을 수 있습니다:

    [array]
    (
        'name' => 'joe'
        'location' => 'UK'
        'gender' => 'male'
    )

    첫번째 파라미터는 오프셋을 설정할수 있게 합니다. 기본값은 3인데 왜냐하면 URI는 일반적으로 컨트롤러/함수 를 첫번째및 두번째 세그먼트로 가지기 때문입니다. 예:

    $array = $this->uri->uri_to_assoc(3);

    echo $array['name'];

    두번째 파라미터로 기본 키 이름을 설정할수 있습니다. 그렇게하면 URI에 해당하는값이 없더라도, 언제나 예상되는 인덱스를 포함한 배열을 리턴합니다. 예:

    $default = array('name', 'gender', 'location', 'type', 'sort');

    $array = $this->uri->uri_to_assoc(3, $default);

    만약 URI 가 여러분의 default에 있는 값을 포함하지 않더라도, 배열인덱스는 지정한 이름으로 설정되며 값은 FALSE 로 설정됩니다.

    마지막으로 , 주어진 키에 대응되는 값을 발견할수 없을때 (URI 세그먼트가 홀수라든지) 값은 FALSE 로 설정됩니다.

    $this->uri->ruri_to_assoc(n)

    이함수는 위의 함수와 동일합니다.다만, CodeIgniter URI 라우팅을 사용하실때 최종적으로 재 라우팅(re-routed) 되는 URI 로부터 연관배열을 생성한다는점만 다릅니다.

    $this->uri->assoc_to_uri()

    연관배열을 입력받아 URI 문자열을 생성합니다. 배열키도 문자열에 포함됩니다. 예:

    $array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red');

    $str = $this->uri->assoc_to_uri($array);

    // 결과: product/shoes/size/large/color/red

    $this->uri->uri_string()

    완전한 URI 문자열을 리턴합니다 . 예를들어 , 전체 URL이 아래와 같다면 :

    http://example.com/index.php/news/local/345

    함수는 아래를 리턴합니다:

    /news/local/345

    $this->uri->ruri_string()

    이 함수는 위의 함수와 완전히 동일합니다.다만, CodeIgniter URI 라우팅을 사용하실때 최종적으로 재 라우팅(re-routed) 되는 URI 를 리턴한다는 점만 다릅니다.

    $this->uri->total_segments()

    세그먼트 전체 개수를 리턴합니다.

    $this->uri->total_rsegments()

    이 함수는 위의 함수와 완전히 동일합니다.다만, CodeIgniter URI 라우팅을 사용하실때 최종적으로 재 라우팅(re-routed) 되는 URI 세그먼트의 전체개수를 리턴한다는 점만 다릅니다.

    $this->uri->segment_array()

    URI 세그먼트를 포함한 배열을 리턴합니다. 예:

    $segs = $this->uri->segment_array();

    foreach ($segs as $segment)
    {
        echo $segment;
        echo '<br />';
    }

    $this->uri->rsegment_array()

    이 함수는 위의 함수와 완전히 동일합니다.다만, CodeIgniter URI 라우팅을 사용하실때 최종적으로 재 라우팅(re-routed) 되는 URI 세그먼트를 포함한 배열을 리턴한다는 점만 다릅니다.

    Pagination Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    페이지네이션 Pagination Class

    CodeIgniter의 페이지네이션 클래스는 매우 사용하기 쉽답니다. 100% 커스터마이징 가능합니다. 커스터마이징은 동적으로 할수도 있고, 설정을 저장할수도 있습니다.

    "페이지네이션" 이라는 말에 익숙하지 않으신가요 ? 바로 아래와같이 페이지 이동을위한 링크를 뜻하는 말이랍니다:

    « First  < 1 2 3 4 5 >  Last »

    예제 Example

    컨트롤러 함수내에서 어떻게 페이지를 생성하는지 보여주는 예제입니다:

    $this->load->library('pagination');

    $config['base_url'] = 'http://example.com/index.php/test/page/';
    $config['total_rows'] = 200;
    $config['per_page'] = 20;

    $this->pagination->initialize($config);

    echo $this->pagination->create_links();

    참고:

    $config 배열에는 설정값들이 들어갑니다. 위와 같이 그배열을 $this->pagination->initialize 함수에 넘겨줍니다. 20개정도의 설정 아이템들이 있지만, 위에서 보여준것은 그중에서 반드시 필요한 세가지 입니다. 아래는 각 아이템에대한 설명입니다:

    보여줄 페이지네이션이 없을경우create_links() 함수는 빈 문자열을 리턴합니다.

    설정을 설정파일에 저장하기 Setting preferences in a config file

    설정을 위처럼 하지않고, 설정파일에 저장할수도 있습니다.pagination.php 파일을 만든후 $config 배열을 추가하세요. 그런후 파일을 config/pagination.php 에 저장하시면, 자동으로 불러지게 됩니다.설정파일로 저장하면 $this->pagination->initialize 함수를 호출할 필요가 없습니다.

    페이지네이션 커스터마이징 하기 Customizing the Pagination

    아래는 페이지네이션이 어떻게 보여질지에 대한 설정(preferences) 목록입니다.

    $config['uri_segment'] = 3;

    페이지네이션 함수는 페이지 번호를 URI 세그먼트의 어느부분에 포함시킬지 자동으로 결정합니다. 여러분이 직접 지정하고싶으면 위 설정을 사용합니다.

    $config['num_links'] = 2;

    선택된 페이지번호 좌우로 몇개의 숫자링크를 보여줄지 설정합니다. 예를들어, 2 는 본 페이지의 맨위에있는 예제와 같이 양쪽에 2개의 숫자링크를 보여줍니다.(즉 숫자는 5개가 되겠죠 )

    $config['use_page_numbers'] = TRUE;

    기본값으로, URI 세그먼트는 페이징하는 아이템들의 시작 인덱스를 사용합니다.(역주:무슨소리인지 잘 모르겠네요.사용해 보면 아는데 시간이 없어서 ... 죄송).실제 페이지 번호를 보여주고 싶다면, TRUE로 설정하세요.

    $config['page_query_string'] = TRUE

    기본값으로, 페이지네이션 라이브러리는 여러분이 URI세그먼트(Segments)를 사용한다고 가정합니다. 그리고 링크를 아래처럼 생성합니다.

    http://example.com/index.php/test/page/20

    $config['enable_query_strings'] 을 TRUE 로 설정하면, 링크는 자동으로 쿼리스트링(Query Strings) 형식으로 바뀝니다. 이 옵션은 명시적으로 설정할수도 있습니다. $config['page_query_string'] 이 TRUE 일때 페이지네이션 링크는 아래처럼 바뀝니다.

    http://example.com/index.php?c=test&m=page&per_page=20

    "per_page"는 기본적으로 전달되는 쿼리스트링입니다. 그러나 $config['query_string_segment'] = 'your_string' 를 통해서 여러분이 설정할수도 있습니다.

    감싸는 태그 추가하기 Adding Enclosing Markup

    페이지네이션 전체에 감싸는 태그를 추가하고싶으면 아래와 같이 합니다:

    $config['full_tag_open'] = '<p>';

    페이지네이션 왼쪽에 위치할 여는태그입니다.

    $config['full_tag_close'] = '</p>';

    페이지네이션 오른쪽에 위치할 닫는태그 입니다.

    "처음으로"링크 커스터마이징 Customizing the First Link

    $config['first_link'] = 'First';

    페이지네이션 맨 왼쪽에 위치할 "처음으로" 링크 글을 설정합니다.First 대신 "처음","맨처음" 등을 쓰시는게 좋겠지요 :)

    값을 FALSE로 설정하면, 이 링크는 렌더링 되지않습니다.

    $config['first_tag_open'] = '<div>';

    "처음으로"링크의 여는태그 입니다.

    $config['first_tag_close'] = '</div>';

    "처음으로"링크의 닫는태그 입니다.

    "끝으로"링크 커스터마이징 Customizing the Last Link

    $config['last_link'] = 'Last';

    페이지네이션 맨 오른쪽에 위치할 "끝으로" 링크 글을 설정합니다.

    값을 FALSE로 설정하면, 이 링크는 렌더링 되지않습니다.

    $config['last_tag_open'] = '<div>';

    "끝으로"링크의 여는태그 입니다.

    $config['last_tag_close'] = '</div>';

    "끝으로"링크의 닫는태그 입니다.

    "다음" 링크 커스터마이징 Customizing the "Next" Link

    $config['next_link'] = '&gt;';

    "다음" 링크 글을 설정합니다.

    값을 FALSE로 설정하면, 이 링크는 렌더링 되지않습니다.

    $config['next_tag_open'] = '<div>';

    "다음"링크의 여는태그 입니다.

    $config['next_tag_close'] = '</div>';

    "다음"링크의 닫는태그 입니다.

    "이전"링크 커스터마이징 Customizing the "Previous" Link

    $config['prev_link'] = '&lt;';

    "이전" 링크 글을 설정합니다.

    값을 FALSE로 설정하면, 이 링크는 렌더링 되지않습니다.

    $config['prev_tag_open'] = '<div>';

    "이전"링크의 여는태그 입니다.

    $config['prev_tag_close'] = '</div>';

    "이전"링크의 닫는태그 입니다.

    "현재페이지"링크 커스터마이징 Customizing the "Current Page" Link

    $config['cur_tag_open'] = '<b>';

    "현재페이지"링크의 여는태그 입니다.

    $config['cur_tag_close'] = '</b>';

    "현재페이지"링크의 닫는태그 입니다.

    링크숫자 커스터마이징 Customizing the "Digit" Link

    $config['num_tag_open'] = '<div>';

    링크숫자 링크의 여는태그 입니다.

    $config['num_tag_close'] = '</div>';

    링크숫자 링크의 닫는태그 입니다.

    페이지 숨기기

    페이지를 숨기고 싶다면(예를 들어 이전,다음 링크만 출력하고 싶다든지) 아래와 같이 하면 해당 페이지가 렌더링 되지않습니다.

    $config['display_pages'] = FALSE;

    모든 링크에 클래스 추가

    페이지네이션 클래스를 통해 생성된 모든 링크에 클래스 속성을 추가하고자 한다면, "anchor_class"를 원하는 클래스 이름으로 설정하면 됩니다.

    Template Parser Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    템플릿 파서 Template Parser Class

    템플릿파서 클래스를 이용하시면 뷰파일에 포함된 모조변수(pseudo-variables)를 파싱할수 있습니다. 단순한 변수나 변수,태그 쌍 모두 파싱가능합니다.템플릿엔진을 사용해보신적이 없나요 ? 모조변수는 아래와같은 형태랍니다:

    <html>
    <head>
    <title>{blog_title}</title>
    </head>
    <body>

    <h3>{blog_heading}</h3>

    {blog_entries}
    <h5>{title}</h5>
    <p>{body}</p>
    {/blog_entries}
    </body>
    </html>

    이변수들은 실재 PHP 변수는 아닙니다. 오히려 일반 텍스트에 가까우며, 이변수들을 통해서 PHP 코드를 템플릿(뷰 파일)에서 제거할 수 있습니다.

    참고: 뷰파일에서 순수 PHP를 사용하시는것이 약간 더 빨리 동작하므로, 본 클래스를 반드시 사용하실필요는 없습니다. 그러나, 어떤 개발자들은 PHP를 모르는 디자이너와 같이 일할때 템플릿 엔진을 사용하는것을 더 선호하는 경우도 있습니다.

    추가 참고: 템플릿파서 클래스는 완전한 템플릿 파싱 솔루션이 아닙니다. 우리는 성능의 극대화 쪽으로 많이 신경썼습니다.

    클래스 초기화 Initializing the Class

    CodeIgniter에 있는 대부분의 다른 클래스들처럼, 파서클래스도 $this->load->library 함수로 초기화 합니다:

    $this->load->library('parser');

    일단 로드되면,파서 라이브러리 객체는 $this->parser 를 통해 사용합니다.

    아래의 함수들이 본 라이브러리에서 사용가능합니다:

    $this->parser->parse()

    이 메소드는 템플릿 이름과 데이터베열을 입력받으며, 파싱된 결과를 생성합니다. 예:

    $this->load->library('parser');

    $data = array(
                'blog_title' => 'My Blog Title',
                'blog_heading' => 'My Blog Heading'
                );

    $this->parser->parse('blog_template', $data);

    첫번째 파라미터는 뷰파일(view file)의 이름(예제에서는 blog_template.php)을 포함하며, 두번째 파라미터는 템플릿에서 대체될 데이터의 연관배열 입니다. 위 예제에서 , 템플릿은 두개의 변수를 포함합니다: {blog_title} 와 {blog_heading}

    "echo"를 사용할 필요가 없으며 $this->parser->parse()함수에서 리턴되는 데이터에대해서 뭔가 작업해줄 필요가 없습니다. 결과는 자동으로 출력클래스로 보내져 브라우저로 전송됩니다. 그러나, 출력클래스로 보내는대신 데이터를 리턴받으시려면 세번째 파라미터를 TRUE 로 설정합니다:

    $string = $this->parser->parse('blog_template', $data, TRUE);

    $this->parser->parse_string()

    parse()와 동일한 동작을 합니다만, 뷰파일 대신에 문자열을 첫번째 파라미터로 받을 수 있다는것이 다릅니다..

    변수 쌍 Variable Pairs

    위의 예제에서는 단순 변수치환을 보여주었습니다. 만약 여러분이 각 반복마다 다른 데이터를 가지고 있는 변수블럭전체를 반복적으로 처리하고싶다면, 본 페이지의 처음에 보여주었던 예제를 보세요:

    <html>
    <head>
    <title>{blog_title}</title>
    </head>
    <body>

    <h3>{blog_heading}</h3>

    {blog_entries}
    <h5>{title}</h5>
    <p>{body}</p>
    {/blog_entries}
    </body>
    </html>

    위 예제를 보시면 변수 쌍이 있다는것을 아실거예요: {blog_entries} 데이터들.. {/blog_entries}. 이런경우 , 이 쌍들 사이에 있는 데이터덩어리들은 여러번 반복되며, 결과셋의 열수에 대응하여 작동됩니다.

    변수쌍은 위의 단순변수치환예제와 동일한 코드로 파싱되나,변수쌍에 대응하는 다차원배열을 추가하셔야 합니다. 다음예제를 참고하시죠:

    $this->load->library('parser');

    $data = array(
                  'blog_title'   => 'My Blog Title',
                  'blog_heading' => 'My Blog Heading',
                  'blog_entries' => array(
                                          array('title' => 'Title 1', 'body' => 'Body 1'),
                                          array('title' => 'Title 2', 'body' => 'Body 2'),
                                          array('title' => 'Title 3', 'body' => 'Body 3'),
                                          array('title' => 'Title 4', 'body' => 'Body 4'),
                                          array('title' => 'Title 5', 'body' => 'Body 5')
                                          )
                );

    $this->parser->parse('blog_template', $data);

    만약 쌍으로 구성된 데이터가 데이터베이스 결과셋이라면 result_array() 함수를 통해서 간단히 다차원 배열을 만들수 있습니다:

    $query = $this->db->query("SELECT * FROM blog");

    $this->load->library('parser');

    $data = array(
                  'blog_title'   => 'My Blog Title',
                  'blog_heading' => 'My Blog Heading',
                  'blog_entries' => $query->result_array()
                );

    $this->parser->parse('blog_template', $data);
    Unit Testing Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    단위테스트 Unit Testing Class

    단위테스트는 소프트웨어 개발의 접근방법중 하나이며, 여러분의 프로그램내의 각 함수마다 테스트를 작성하는것입니다. 이런 컨셉이 익숙하지않으시면 인터넷검색을 통해서 먼저 알아보시는것이 좋습니다.

    CodeIgniter의 단위테스트 클래스는 매우 심플하며 ,검사함수와 두개의 결과함수로 이루어져 있습니다.또한 완전한 단위테스트 수트(suite)는 아니며 ,여러분의 코드가 올바른 데이터형 및 올바른 결과를 생성하는지 검증하는 단순한 방법을 제공하는데 초점이맞추어져 있습니다.

    클래스 초기화 Initializing the Class

    다른 클래스들과 마찬가지로 , 단위테스트 클래스도 컨트롤러에서 $this->load->library 함수를 통해 초기화 합니다:

    $this->load->library('unit_test');

    일단 로드되면 단위테스트 객체는 $this->unit 로 사용하실 수 있습니다.

    테스트 실행 Running Tests

    아래 나오는 함수에 테스트와, 예상되는 결과를 넘겨주는것으로 테스트를 실행할수 있습니다:

    $this->unit->run( test, expected result, 'test name', 'notes');

    test 는 여러분이 테스트하기를 위하는 코드의 결과이며, expected result 는 예상하는 결과(혹은 데이터형), 그리고 test name 은 선택사항으로서 여러분의 테스트에 이름을 부여할때 사용합니다.또한 메모를 입력하고 싶다면 notes 부분에 입력하세요.

    예:

    $test = 1 + 1;

    $expected_result = 2;

    $test_name = 'Adds one plus one';

    $this->unit->run($test, $expected_result, $test_name);

    글자그대로 일치하는것을 검사하는지 데이터형이 일치하는것을 검사하는지에 따라서 ' 예상되는 결과'부분은 달라집니다.
    아래는 글자그대로가 일치하는지 검사합니다:

    $this->unit->run('Foo', 'Foo');

    아래는 데이터형이 일치하는지를 검사합니다:

    $this->unit->run('Foo', 'is_string');

    두번째 파라미터로"is_string"을 사용했다는걸 아실수 있겠지요 .이것은 테스트(test)가 문자열을 결과로 생성하는지 여부를 검증해라 라고 하는것과 같습니다.
    아래는 각 타입별 파라미터값입니다 :

    리포트 생성 Generating Reports

    여러분은 테스트결과를 각 테스트수행후 볼수도 있고, 여러개의 테스트를 수행한후 마지막으로 리포트를 생성하게 할수도 있습니다. 직접적이고 심플하게 리포트를 표시하려면 run를 echo 나 return 하시면 됩니다:

    echo $this->unit->run($test, $expected_result);

    모든테스트에 대한 전체 리포트를 보시려면 아래와같이 합니다:

    echo $this->unit->report();

    리포트는 HTML 테이블 형태로 생성됩니다. 만약 원래데이터만 보시려면 아래함수로 배열을 추출해 낼 수 있습니다:

    echo $this->unit->result();

    엄격 모드 Strict Mode

    기본값으로, 단위테스트클래스는 '글자그대로일치'를 느슨하게 검사합니다. 아래 예제를 보세요:

    $this->unit->run(1, TRUE);

    테스트는 정수를 검사하나, 예상되는 값으로는 불린(boolean) 값을 넘겨주었습니다. 그러나 , PHP의 느슨한 데이터형 설정(data-typing) 때문에 일반적인 일치테스트를 사용하게되어 위 결과는 TRUE 가 됩니다:

    if (1 == TRUE) echo 'This evaluates as true';

    원한다면 단위테스트클래스를 엄격모드로 설정할수 있습니다. 그러면 데이터형과 값을 동시에 검사합니다.:

    if (1 === TRUE) echo 'This evaluates as FALSE';

    엄격모드를 활성화 하려면 아래와 같이 합니다:

    $this->unit->use_strict(TRUE);

    단위테스트 활성/비활성화 Enabling/Disabling Unit Testing

    테스트 코드를 프로그램안에 남겨두되 , 원할때만 수행되도록 하려면, 아래함수를 사용하여 테스팅을 비활성화 할수 있습니다:

    $this->unit->active(FALSE)

    단위 테스트의 결과 표시

    단위 테스트의 결과는 다음 항목이 기본적으로 표시됩니다 :

    $this->unit->set_items()를 이용해서 어떤 항목이 표시될지 설정할 수 있습니다.만약, 테스트 이름과 결과만을 표시하려면 :

    테스트 결과 표시 설정

    $this->unit->set_test_items(array('test_name', 'result'));

    템플릿 제작 Creating a Template

    테스트결과의 포멧을 기본설정과 다르게 하고싶다면 직접 템플릿을 작성하실 수 있습니다.여기 간단한 템플릿 예제가 있습니다 . 반드시 필요한 모조변수(pseudo-variables)에 주의하세요:

    $str = '
    <table border="0" cellpadding="4" cellspacing="1">
        {rows}
            <tr>
            <td>{item}</td>
            <td>{result}</td>
            </tr>
        {/rows}
    </table>';

    $this->unit->set_template($str);

    참고: 템플릿은 단위테스트를 수행하기전에 선언되어야 합니다.

    Loader Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    로더 Loader Class

    로더는 이름처럼 각 요소를 로드하는데 사용합니다. 요소는 라이브러리(클래스)일수도 있고 뷰파일, 헬퍼, 모델, 혹은 여러분이 만든파일일수도 있습니다.

    참고: 이 클래스는 자동으로 초기화 됩니다.

    아래함수들이 이 클래스에서 사용가능합니다:

    $this->load->library('class_name', $config, 'object name')

    이함수는 핵심( core)클래스를 로드하기위해서 사용합니다. class_name 은 로드하고자하는 클래스의 이름입니다. 참고: 우리는 "class" 와 "library" 교대로 사용합니다.

    예를들어, 만약 CodeIgniter를 이용하여 이메일을보내고자 한다면 , 먼저 컨트롤러에서 이메일 클래스를 로드합니다:

    $this->load->library('email');

    일단 로드되면, 라이브러리는 사용가능상태가 되고, $this->email->some_function(). 와 같이 사용합니다.

    라이브러리파일은 "libraries" 폴더의 하위디렉토리에 저장될수 있으며, 여러분의 개인적인 application/libraries 폴더에 저장될수도 있습니다. 하위디렉토리에 저장된 파일을 로드하려면, "libraries"폴더로부터의 상대경로를 포함시키면 됩니다. 예를들어 , 다음위치에 파일이 있다면:

    libraries/flavors/chocolate.php

    다음과 같이 로드합니다:

    $this->load->library('flavors/chocolate');

    여러분은 얼마든지 원하는만큼 깊이에 있는 하위디렉토리에서 파일을 불러올 수 있습니다.

    또한 여러 개의 라이브러리를 한번에 로드하고자 한다면 배열을 넘겨주면 됩니다.

    $this->load->library(array('email', 'table'));

    옵션 설정 Setting options

    두번째 파라미터는 선택적으로 설정정보를 넘겨줄 수 있습니다. 일반적으로 아래와 같이 배열을 넘겨줍니다:

    $config = array (
                      'mailtype' => 'html',
                      'charset'  => 'utf-8,
                      'priority' => '1'
                   );

    $this->load->library('email', $config);

    설정옵션은 통상 설정파일을 통해 설정할 수 있습니다. 각 라이브러리페이지에는 상세한 정보가 기술되어있으니 , 사용하고자하는 부분에대한정보는 그곳을 참고해주세요.

    주의: 첫번째 파라미터(로드할 라이브러리)로 배열을 넘겨주었다면, 각 라이브러리는 같은 설정정보를 받게 됩니다.

    라이브러리를 다른 객체이름으로 할당하기 Assigning a Library to a different object name

    세번째 파라미터가 비어있다면, 라이브러리는 통상 객체에 라이브러리와 같은 이름을 할당합니다. 예를들어, 라이브러리 이름이 Session이라면 변수명을$this->session로 할당합니다.

    만약 다른클래스이름으로 사용하고싶다면 세번째 파라미터로 넘기시면 됩니다:

    $this->load->library('session', '', 'my_session');

    // Session class is now accessed using:

    $this->my_session

    첫번째 파라미터에 배열을 넘겨주었다면, 세번째 파라미터는 무시됩니다.

    $this->load->view('file_name', $data, true/false)

    이 함수는 뷰파일을 로드합니다. 만약 뷰(Views) 섹션을 읽지않으셨다면, 먼저 읽어주세요 . 이함수가 일반적으로 어떻게 쓰이는지 알 수 있습니다.

    첫번째 파라미터는 꼭 필요합니다 . 로드하고자하는 뷰파일의 이름이기 때문입니다. 참고: .php 가 아닌 다른 파일을 사용하는경우가 아니라면 .php를 적어주실필요가 없습니다.

    선택적으로 사용하는 두번째 파라미터는 연관배열이나, 객체를 입력받으며,PHP extract 함수를 이용하여 뷰파일에서 사용가능한 변수로 변환합니다.

    선택적으로 사용하는 세번째 파라미터는 함수의 기능을 변경하여 문자열을 브라우저로 보내는대신 리턴하게 합니다. 특정한 방법으로 데이터를 처리하고자하는 경우 유용합니다.파라미터를true 로 설정하면 데이터를 리턴합니다. 기본설정은false이며 데이터를 브라우저로 전송합니다. 데이터를 리턴받을때는 아래와같이 변수에 할당해야합니다:

    $string = $this->load->view('myfile', '', true);

    $this->load->model('Model_name');

    $this->load->model('Model_name');

    모델이 하위디렉토리에 존재한다면 모델폴더로부터의 상대경로를 적어주세요. 예를들어, 모델이 application/models/blog/queries.php 에 있다면 ,다음과같이 합니다:

    $this->load->model('blog/queries');

    모델에 다른 객체이름을 할당하고싶다면 두번째 파라미터로 넘겨주시면 됩니다:

    $this->load->model('Model_name', 'fubar');

    $this->fubar->function();

    $this->load->database('options', true/false)

    이함수는 데이터베이스 클래스를 로드합니다. 두개의 파라미터는 선택적(optional)으로 사용합니다. 더 자세한정보는 데이터베이스(database) 섹션을 참고하세요.

    $this->load->vars($array)

    이 함수는 연관배열을 입력받아 PHP extract 함수를 통해 변수를 생성합니다. 이 함수는 위의 $this->load->view() 함수에서 두번째 파라미터를 사용한 경우와 같은 결과를 보여줍니다. 만약 컨트롤러의 생성자에서 전역변수를 설정하여 모든함수에서 로드한 뷰에 모두 사용할수 있도록 하려면 이함수를 사용합니다. 이함수를 여러번 호출할 수도 있습니다. 데이터는 캐시되고 합쳐져서 하나의 배열이 된 다음 변수로 변환됩니다.

    $this->load->get_var($key)

    뷰에서 사용가능한 연관배열을 체크합니다. 어떤 변수가 라이브러리나 컨트롤러에서 $this->load->vars()를 통해 설정된 경우 유용합니다.

    $this->load->helper('file_name')

    이함수는 헬퍼를 로드합니다.file_name_helper.php 를 제외한 파일이름 입니다.

    $this->load->file('filepath/filename', true/false)

    이 함수는 일반적인 파일 로딩 함수입니다. 첫번째 파라미터로 파일경로와 이름을 입력하면 해당파일을 연다음 읽습니다. 기본값으로 , 뷰파일처럼 데이터를 브라우저로 보냅니다. 두번째 파라미터를 true 로 설정하면 데이터를 문자열로 리턴합니다.

    $this->load->language('file_name')

    이함수는 언어로딩함수(language loading function)의 별칭( alias) 입니다 :$this->lang->load()

    $this->load->config('file_name')

    이함수는 설정로딩함수(config file loading function)의 별칭( alias) 입니다: $this->config->load()

    응용 프로그램 패키지

    An application package allows for the easy distribution of complete sets of resources in a single directory, complete with its own libraries, models, helpers, config, and language files. It is recommended that these packages be placed in the application/third_party folder. Below is a sample map of an package directory

    예제:"Foo Bar" 프로그램의 디렉토리 구성

    아래는 "Foo Bar" 프로그램의 디렉토리 구성 예입니다.

    /application/third_party/foo_bar

    config/
    helpers/
    language/
    libraries/
    models/

    "Foo Bar"가 어떤 프로그램이든 간에 설정파일(config files), 헬퍼(helpers), 언어(language files), 라이브러리(libraries),모델(models)을 포함하고 있습니다. 이런 리소스들을 컨트롤러에서 사용하려면 로더에게 리소스를 패키지에서 불러올것이라고 알려줘야합니다. 알려주기 위해서는 패키지 경로를 추가 해주면 됩니다.

    $this->load->add_package_path()

    패키지 경로를 추가해 주면, 로더 클래스는 리소스에 대한 요청이 있을때 추가된 경로를 그 앞에 붙여줍니다.예를 들어, "Foo Bar" 프로그램 패키지는 Foo_bar.php라는 라이브러리를 가지고 있습니다.컨트롤러에서는 아래와 같이 합니다:

    $this->load->add_package_path(APPPATH.'third_party/foo_bar/');
    $this->load->library('foo_bar');

    $this->load->remove_package_path()

    컨트롤러가 패키지에 있는 리소스를 더이상 사용할 필요가 없으면 패키지 경로를 제거할 수 있습니다. 패키지경로가 제거되면, 로더는 더이상 그 경로에서 리소스를 찾지 않습니다. 맨 마지막에 추가된 경로를 제거하려면 파라미터없이 이 함수를 호출해 주면 됩니다.

    $this->load->remove_package_path()

    특정 경로를 제거하려면 add_package_path() 에서 설정한 경로와 같은 값을 파라미터로 넘겨주세요.

    $this->load->remove_package_path(APPPATH.'third_party/foo_bar/');

    패키지 뷰 파일(Package view files)

    기본값으로, 패키지 뷰 파일경로는 add_package_path() 가 호출될때 설정됩니다.뷰파일이 로드될 때는 설정된 뷰 경로에서 루프를 돌면서 첫번째로 일치하는 뷰파일이 로드됩니다.

    이런경우, 패키지 내에서 뷰파일 이름이 충돌 하여, 잘못된 패키지가 로드될 가능성이 있습니다.그럴 가능성을 없애기 위해서add_package_path() 를 호출할 때 두번째 파라미터를 FALSE 로 설정하세요.

    $this->load->add_package_path(APPPATH.'my_app', TRUE);
    $this->load->view('my_app_index'); // 로드됨
    $this->load->view('welcome_message'); //두번째 파라미터가 TRUE 이므로 기본 welcome_message b/c 가 로드 되지않습니다.

    // 리셋
    $this->load->remove_package_path(APPPATH.'my_app');

    // 두번째 파라미터가 없는경우
    $this->load->add_package_path(APPPATH.'my_app', TRUE);
    $this->load->view('my_app_index'); // 로드됨
    $this->load->view('welcome_message'); // 로드됨
    Benchmarking Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    벤치마크 Benchmarking Class

    CodeIgniter에는 항상 활성화되어있는 벤치마크 클래스가 포함되어있습니다.이 클래스로 어떤 두 지점(marked points) 사이의 시간 간격을 계산할수 있습니다.

    Note: 이 클래스는 시스템이 자동으로 초기화하기때문에 수동으로 할 필요가 없습니다.

    벤치마크는 프레임워크가 호출되는 순간 언제나 시작되며, 최종적으로 뷰페이지가 브라우저로 전송되기 직전에 종료됩니다. 이러한 특성이 시스템 동작시간을 상당히 정확하게 측정할수 있습니다.

    목차

    벤치마크 클래스 사용방법

    벤치마크 클래스는 컨트롤러, , 혹은 모델에서 사용할 수 있습니다.사용방법은 다음과 같습니다:

    1. 시작포인트를 설정(Mark)한다
    2. 끝 포인트를 설정한다.
    3. "elapsed time" 함수를 실행하여 결과를 확인한다.

    실재 사용사례입니다:

    $this->benchmark->mark('code_start');

    // Some code happens here

    $this->benchmark->mark('code_end');

    echo $this->benchmark->elapsed_time('code_start', 'code_end');

    Note: "code_start" 나 "code_end" 는 여러분이 임의로 정할 수 있습니다.. 단지 두 지점을 설정하기 위한 말일뿐입니다. 당신은 어떤 말이든 원하는대로 집어넣을수 있고 , 몇개의 마커(markers)를 설정해도 상관이 없습니다. 다음예제를 봐주세요 :

    $this->benchmark->mark('dog');

    // Some code happens here

    $this->benchmark->mark('cat');

    // More code happens here

    $this->benchmark->mark('bird');

    echo $this->benchmark->elapsed_time('dog', 'cat');
    echo $this->benchmark->elapsed_time('cat', 'bird');
    echo $this->benchmark->elapsed_time('dog', 'bird');

    설정한 벤치마크 포인트에서 성능검사하기(Profiling Your Benchmark Points)

    벤치마크 데이터를 프로파일러 에서 사용할 수 있습니다.그러기 위해서는 설정된 마크(marks)들이 모두 짝을 이루어야하며, 각 마크 포인트(mark poin)이름은 반드시 _start_end로 끝나야합니다. 각 쌍의 마크포인트 이름은 _start,_end 부분을제외하고 반드시 동일해야합니다.예:

    $this->benchmark->mark('my_mark_start');

    // Some code happens here...

    $this->benchmark->mark('my_mark_end');

    $this->benchmark->mark('another_mark_start');

    // Some more code happens here...

    $this->benchmark->mark('another_mark_end');

    더 자세한정보는 프로파일러 페이지를 참고하세요 .

    전체수행시간 표시

    CodeIgniter 가 시작하여 최종 출력이 브라우저로 보내질때까지의 전체시간을 표시하고싶다면 뷰 페이지에 아래의 코드를 삽입하시면 됩니다.<?php echo $this->benchmark->elapsed_time();?>

    위코드를 보시면 두개의 포인트사이에서 시간경과를 측정하던 함수와 동일한 함수를 사용한다는것을 알수 있습니다. 파라미터가 없다면 CI 는 전체시간을 최종출력이 이루어질때까지 계속 시간을 측정합니다. 그러므로 어느위치에 이 코드를 삽입하든 최종출력이 브라우저로 전송될때까지의 시간을 측정한다는점에는 차이가 없으므로 위치에 구애받지 않으셔도 됩니다.

    PHP 코드를 쓰는게 귀찮으시면, 아래의 축약 코드를 써도 같은 결과를 얻으실 수 있습니다.

    {elapsed_time}

    Note: 만약 벤치마크를 컨트롤러에서 수행한다면 반드시 시작/끝 포인트를 지정하셔야 합니다.

    메모리 사용량 표시

    만약 설치된 PHP 가 --enable-memory-limit 설정(configured with --enable-memory-limit)과 함께 설치되었다면, 전체시스템에서 사용된 메모리의 총량을 표시하실 수 있습니다. 아래의 코드를 참고하세요 .

    <?php echo $this->benchmark->memory_usage();?>

    Note:이 함수는 오직 뷰 파일에서만 쓸수있습니다. 사용량은 전체 어플리케이션에서 사용된 총량을 반영합니다.

    PHP 코드를 쓰는게 귀찮으시면, 아래의 축약 코드를 써도 같은 결과를 얻으실 수 있습니다.

    {memory_usage}
    Security Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    보안 클래스

    보안클래스는 입력 값을 안전히 처리하여, 보다 안전한 프로그램을 만드는데 도움이 되는 메서드들을 제공합니다.

    XSS 필터링

    CodeIgniter에서는 크로스 사이트 스크립팅 공격을 방지하기 위해 모든 POST 와 COOKIE 데이터를 자동으로 필터링 할 수도 있고, 개별 아이템별로 필터링 할 수도 있습니다. 전역적으로 동작하지 않는것이 기본값입니다.왜냐하면, 처리시 약간의 오버헤드가 존재하기도 하고, 개발자에게 선택권을 주기 위해서 입니다.

    XSS 필터는 자바스크립트실행을 시도한다거나, 쿠키를 하이재킹한다거나, 다른 해괴망측한 짓거리들을 한다거나 하는것을 막는 기술입니다.만약 금지된 문자나 코드(위 짓거리들을 하려는)등을 찾으면 데이터를 안전한 HTML 엔터티로 변환하여 표시합니다.

    안내: 이기능은 입력데이터 처리용으로만 사용하세요 . 처리시 오버헤드가 심해질수 있으므로(시스템 리소스 많이먹음) 다른 처리에서는 사용하지 않는것이 좋습니다.

    XSS필터를 이용하여 필터하려면 아래 함수를 사용하세요:

    $this->security->xss_clean()

    사용예:

    $data = $this->security->xss_clean($data);

    항상 자동으로 POST 및 COOKIE 데이터를 필터링하려면 application/config/config.php 를 열고 다음과 같이 설정하십시오.

    config['global_xss_filtering'] = TRUE;

    안내: form validation 클래스에도 XSS 필터링 기능을 사용할 수 있는 옵션이 있습니다.

    옵션으로 제공되는 두번째 파라미터 is_image는 이미지를 검사하여 잠재적 XSS 공격을 방지합니다. 파일업로드시 유용합니다. 두번째 파라미터가 TRUE이면 처리된 문자열을 반환하는 대신 이미지가 안전한 경우 TRUE를, 악의적인 정보가 포함된 경우 FALSE를 반환합니다.

    if ($this->security->xss_clean($file, TRUE) === FALSE)
    {
        // file failed the XSS test
    }

    $this->security->sanitize_filename()

    사용자 입력에서 파일이름을 입력받을 경우 디렉토리 탐색이나 다른 보안문제를 해결하기 위해서 소독과정을 거치는것이 좋습니다.(손소독 아님 ㅎㅎ). sanitize_filename() 메서드를 이용하여 파일이름을 소독하세요. 예:

    $filename = $this->security->sanitize_filename($this->input->post('filename'));

    파일이름에 상대경로가 포함되는걸 허용할 경우 (예:file/in/some/approved/folder.txt) 두번째 파라미터$relative_path 를TRUE로 설정하세요.

    $filename = $this->security->sanitize_filename($this->input->post('filename'), TRUE);

    크로스 사이트 요청 위조 Cross-site request forgery (CSRF)

    CSRF 보호를 활성화하려면 application/config/config.php 를 열고 다음과 같이 설정합니다:

    $config['csrf_protection'] = TRUE;

    폼헬퍼(form helper)의 form_open() 함수를 사용하면 폼의 CSRF 보호를위한 hidden 필드가 자동으로 삽입됩니다.

     

    File Uploading Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    파일 업로드 File Uploading Class

    CodeIgniter의 파일 업로딩 클래스는 파일을 업로드 할 수 있도록 해줍니다.다양한 설정옵션이 있으며 , 파일타입이나 크기등을 제한할 수 있습니다.

    절차 The Process

    파일을 업로드하는 과정은 다음의 일반적차를 따릅니다:

    이 과정을 보여주기 위하여 간단한 튜토리얼을 보여드립니다. 그리고 그 아래 참조가이드를 제공합니다.

    업로드 폼 생성 Creating the Upload Form

    텍스트에디터를 사용하여 upload_form.php이라는 폼을 파일을 생성합니다. 그리고 아래 코드를 삽입한후 applications/views/ 폴더 아래 저장합니다:

    위코드를 보시면 form 헬퍼를 사용하여 여는 form 태그대신 사용한것을 알수 있습니다. 파일업로드는 multipart form을 필요로 하므로 헬퍼는 적당한 태그를 자동으로 작성해줍니다. 그리고 $error 변수가 있다는것을 알수 있으실 것입니다. 이 변수는 사용자의 실수에 대해서 에러메세지를 보여줍니다.

    성공 페이지 The Success Page

    텍스트 에디터를 이용하여 upload_success.php파일을 작성합니다. 그리고 그 안에 아래 코드를 삽입한후 applications/views/ 폴더 아래 저장합니다:

    컨트롤러 The Controller

    텍스트 에디터를 이용하여 upload.php라는 이름의 컨트롤러 파일을 작성한후 아래의 코드를 삽입하고 applications/controllers/ 폴더 아래 저장합니다.:

    업로드 폴더 The Upload Folder

    업로드 한 이미지를 저장할 대상폴더가 필요합니다.CodeIgniter 가 설치된 루트폴더에 uploads 라는폴더를 생성하고 권한을 777로 합니다.

    시험해보세요! Try it!

    작성한 폼을 테스트하기위해 아래와 유사한 경로로 접근합니다:

    example.com/index.php/upload/

    업로드 폼을 보실수 있으실겁니다. 이미지 파일( jpg, gif, png 등)업로드를 시도해보세요 .컨트롤러의 경로가 올바르다면 제대로 작동하는것을 확인하실 수 있습니다.

     

    참조 가이드 Reference Guide

    업로드 클래스 초기화 Initializing the Upload Class

    CodeIgniter의 다른 클래스들과 마찬가지로 ,컨트롤러에서 $this->load->library 함수를 이용하여 초기화 합니다:

    $this->load->library('upload');

    업로드 클래스가 로드되면 , $this->upload 과 같이 업로드 객체를 사용하실 수 있습니다.

    설정하기 Setting Preferences

    다른 라이브러리들과 마찬가지로 , 어떤 파일이 업로드 허용될지 설정할 수 있습니다.위에서 만든 컨트롤러에서 아래의 설정을 추가해보세요 :

    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width'] = '1024';
    $config['max_height'] = '768';

    $this->load->library('upload', $config);

    // Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class:
    $this->upload->initialize($config);

    위 설정은 대부분 무엇을 뜻하는지 직관적으로 알수 있으실겁니다. 아래 테이블은 가능한 설정들을 보여줍니다.

    설정들 Preferences

    아래의 설정들이 사용가능합니다.설정을 명시하지않을경우 사용될 기본값들도 확인하세요 .

    설정 기본값 옵션 설명
    upload_path None None 업로드 파일이 위치할 폴더경로 .폴더는 쓰기 가능해야하며 경로는 절대경로 혹은 상대경로를 사용합니다.
    allowed_types None None 업로드를 허용할 파일의 마임타입(mime types)을 설정합니다. 보통 파일 확장자는 마임타입으로 사용될수 있습니다. 멀티플타입은 파이프를 이용하여 구분합니다.
    overwrite FALSE TRUE/FALSE (boolean) true 로 설정된 상태에서, 같은 이름의 파일이 이미 존재한다면 덮어쓸것입니다. false 로 설정되어있으면, 파일명에 숫자가 추가로 붙게됩니다.
    max_size 0 None 업로드 파일의 최대크기(KB)를 지정합니다. 0으로 설정하면 크기 제한이 없게됩니다.대부분의 PHP는 php.ini 파일에 업로드 파일 크기 설정이 이미 되어있습니다.일반적으로 2 MB ( 2048 KB)가 기본입니다.
    max_width 0 None 업로드 파일의 최대 너비(픽셀단위) 를 설정합니다. 0 이면 제한이 없습니다.
    max_height 0 None 업로드 파일의 최대 높이(픽셀단위)를 설정합니다. 0이면 제한이 없습니다.
    max_filename 0 None 파일이름의 최대길이를 지정합니다.0이면 제한이 없습니다..
    encrypt_name FALSE TRUE/FALSE (boolean) TRUE로 설정하면 파일이름은 랜덤하게 암호화된 문자열로 변합니다. 파일을 업로드한 사람이 파일명을 알수 없도록할때 유용합니다.
    remove_spaces TRUE TRUE/FALSE (boolean) TRUE로 설정하면 파일명에 공백이 있을경우 밑줄(_)로 변경됩니다.이 옵션은 사용을 권장합니다.

    설정파일에서 설정하기 Setting preferences in a config file

    위 설정들을 컨트롤러대신 설정파일에서 할수도 있습니다. 먼저 upload.php파일을 생성한후 $config 배열을 그 안에 만듧니다. 그런다음 그 파일을 config/upload.php 로 저장하면 자동으로 설정이 적용될것입니다. 그려면 $this->upload->initialize 함수를 사용할 필요가 없습니다.

    함수들 Function Reference

    아래 함수들이 사용가능합니다.

    $this->upload->do_upload()

    여러분의 설정에 따라 업로드를 수행합니다.참고: 기본설정은 파일이 userfile라는 폼필드로부터 업로드 될것이라고 기대합니다.또한 폼은 multipart 타입이라야 합니다.:

    <form method="post" action="some_action" enctype="multipart/form-data" />

    필드명을 여러분이 저장하고싶다면 do_upload 함수에 아래와같이 그 이름을 파라미터로 넘겨주시면 됩니다.:

    $field_name = "some_field_name";
    $this->upload->do_upload($field_name)

    $this->upload->display_errors()

    do_upload() 함수가 실패했을때 에러메시지를 추출해줍니다. 이 함수는 자동으로 echo 까지 수행해주지는 않습니다. 단지 데이터만 전달해줄뿐이므로 그 후처리는 여러분이 원하는대로 할 수 있습니다..

    에러메세지 포멧설정 Formatting Errors

    기본으로 위함수는 에러를 <p> 태그들로 감쌉니다. 여러분은 아래와같은 방법으로 다른 구분자를 설정할 수 있습니다.:

    $this->upload->display_errors('<p>', '</p>');

    $this->upload->data()

    업로드한 파일에 관련된 모든 데이터를 배열의 형태로 리턴해주는 헬퍼 함수 입니다.다음 프로토타입을 참조하세요 :

    Array
    (
        [file_name]    => mypic.jpg
        [file_type]    => image/jpeg
        [file_path]    => /path/to/your/upload/
        [full_path]    => /path/to/your/upload/jpg.jpg
        [raw_name]     => mypic
        [orig_name]    => mypic.jpg
        [file_ext]     => .jpg
        [file_size]    => 22.2
        [is_image]     => 1
        [image_width]  => 800
        [image_height] => 600
        [image_type]   => jpeg
        [image_size_str] => width="800" height="200"
    )

    설명 Explanation

    위 배열 아이템에대한 설명입니다..

    아이템 설명
    file_name 업로드한 파일이름입니다. 확장자까지 포함합니다.
    file_type 파일의 마임타입(Mime type)입니다.
    file_path 파일의 서버상 절대경로입니다.
    full_path 파일이름까지 포함한 서버상의 절대경로입니다.
    raw_name 확장자 없는 파일명입니다.
    orig_name 원래파일 이름입니다. 파일이름을 암호화 하는 옵션을 사용한경우에만 유용합니다.
    file_ext 점을 포함한 파일 확장자입니다.
    file_size 킬로바이트(KB)로 표시된 파일 크기입니다.
    is_image 파일이 이미지인지 아닌지를 나타냅니다. 1 = 이미지. 0 = 이미지아님.
    image_width 이미지 너비.
    image_heigth 이미지 높이.
    image_type 이미지 타입. 일반적으로 점이 없는 파일 확장자 입니다.
    image_size_str 이미지의 너비와 높이를 포함하는 문자열입니다. 이미지 태그에 삽입할때 유용합니다.
    Session Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    세션 Session Class

    세션클래스는 사용자의 상태를 관리하고 사이트에서 하는 행위를 추적할수 있도록 해줍니다.세션클래스는 각 사용자에대한 정보를 직렬화하여 쿠키에 저장합니다.이때 필요하다면 암호화도 같이 할수 있습니다. 보안을 강화하기 위하여 세션데이터를 데이터베이스 테이블에 저장할수도 있습니다.이때 세션아이디는 사용자의 쿠키에 저장되며 이 아이디를 가지고 매칭되는 정보를 데이터베이스에서 찾게 됩니다. 기본값은 쿠키에 저장하는것입니다. 만약 데이터베이스에 저장하고자한다면 아래에 설명한 대로 세션테이블을 만들어야합니다.

    참고: 세션클래스는 PHP에 내장된 세션을 사용하지 않습니다. 자체적인 세션데이터를 생성하여 보다 유연하게 개발할수 있도록 해 줍니다.

    참고: 암호화 세션을 사용하지 않는 경우에도 설정 파일에서 encryption key 를 지정하지 않으면 안됩니다. 제삼자에 의한 세션 데이터 조작을 방지합니다.

    세션 초기화 Initializing a Session

    세션은 통상 페이지 로드와 함께 전역적으로 동작하므로 세션클래스는 컨트롤러(controller)의 생성자에서 초기화 하거나 시스템이 자동로드 하도록 해야합니다.대부분 세션클래스는 백그라운드에서 스스로 동작하므로 간단히 클래스를 초기화하는것으로 세션을 읽고,생성하고, 업데이트할 수 있게 됩니다.

    세션클래스를 컨트롤러의 생성자에 직접 등록하시려면 $this->load->library 함수를 이용합니다:

    $this->load->library('session');

    일단 로드되면 , 세션 라이브러리객체는 $this->session 로 접근합니다.

    세션을 어떻게 작동하는가 How do Sessions work?

    페이지가 로드되었을때 , 세션클래스는 사용자의 세션쿠키에 유효한 세션데이터가 있는지를 확인합니다. 세션데이터가 없다면(혹은 유효기간이 지났다면) 새로운 세션이 생성되어 쿠키에 저장됩니다. 세션이 있다면, 그 세션의 정보가 업데이트되고 쿠키도 업데이트 됩니다. 각 업데이트에서 , 세션아이디(session_id)가 생성됩니다.

    한번 초기화되면 세션클래스는 자동으로 동작한다는점을 명심하세요 . 위에서 설명한 작업을 위해서 여러분이 직접하셔야할 일은 없습니다. 아래에서 보여주는대로 세션데이터를 조작하거나,여러분이 만든 데이터를 사용자의 세션에 넣거나 할수 있습니다. 그러나 읽고,쓰고,업데이트하고 하는것은 자동으로 이루어 집니다.

    세션데이터는 무엇인가 What is Session Data?

    CodeIgniter에서 세션은 다음 정보를 포함하는 배열입니다:

    위 데이터들은 아래의 형태를 가지며 , 직렬화(serialized)되어 쿠키에 저장됩니다:

    [array]
    (
         'session_id'    => random hash,
         'ip_address'    => 'string - user IP address',
         'user_agent'    => 'string - user agent data',
         'last_activity' => timestamp
    )

    암호화 옵션이 활성화 되어있으면, 쿠키에 저장하기 전에 직렬화된 배열은 암호화되어 보안수준이 높아지고 다른사람에 의해 읽히거나 조작되는것을 방지할수 있습니다. 암호화에대해 더 자세한정보는 여기를 참조하세요. 세션클래스가 데이터의 초기화 및 암호화를 책임집니다.

    참고: 부하를 줄이기위해서 세션쿠키는 5분(기본값)에 한번만 업데이트 됩니다.만약 한페이지를 반복적으로 새로고침하시면 마지막행동(last activity)시간값이 쿠키가 생성된후 5분이상지냐야 업데이트 되는것을 확인하실 수 있습니다. 시간설정은 system/config/config.php 파일의 $config[sess_time_to_update] 에서 가능합니다.

    세션데이터 가져오기 Retrieving Session Data

    아래 함수를 이용하시면 세션배열에 있는 어떤정보라도 가져올수 있습니다:

    $this->session->userdata('item');

    item 은 가져오고자하는 데이터의 배열 인덱스입니다. 예를들어, 세션아이디를 가져오려면 아래와같이 합니다:

    $session_id = $this->session->userdata('session_id');

    참고: 접근하고자하는 아이템이 존재하지 않는경우에는 FALSE 를 리턴합니다.

    직접 세션데이터를 만들어 추가하기 Adding Custom Session Data

    세션배열의 유용한 부분은 여러분이 직접만든 데이터를 추가하여 사용자의 쿠키에 저장할수 있다는 점입니다. 왜 이게 필요할까요? 여기 하나의 예제가 있습니다:

    특정 사용자가 사이트에 접속했다고 칩시다. 일단 로그인하면, 사용자의 아이디와 이메일주소를 세션쿠키에 저장할수 있습니다. 그러면 , 데이터베이스에 접근할 필요없이 그 정보를 전역적으로 사용할수 있게 됩니다.

    여러분의 데이터를 세션에 추가하려면, 데이터가 들어있는 배열을 아래와같이 넘겨줍니다:

    $this->session->set_userdata($array);

    $array 는 여러분의 데이터가 들어있는 연관배열입니다. 예:

    $newdata = array(
                       'username'  => 'johndoe',
                       'email'     => 'johndoe@some-site.com',
                       'logged_in' => TRUE
                   );

    $this->session->set_userdata($newdata);

    만약 데이터를 한번에 하나만 추가하고싶다면, 아래와같이하시면됩니다

    $this->session->set_userdata('some_name', 'some_value');

    참고: 쿠키의 저장용량은 4KB 가 한계입니다, 그러므로 그 한계치를 넘지않도록 주의하세요 . 특정 암호화 프로세스는 원본데이터보다 더 긴 데이터를 생성하므로, 항상 데이터 길이에 신경쓰셔야 합니다.

    모든 세션 데이터 추출

    모든 사용자 데이터를 배열로 리턴합니다:

    $this->session->all_userdata()

    아래와 같은 형태입니다:

    Array
    (
        [session_id] => 4a5a5dca22728fb0a84364eeb405b601
        [ip_address] => 127.0.0.1
        [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7;
        [last_activity] => 1303142623
    )
    

    세션데이터의 제거 Removing Session Data

    set_userdata() 함수가 데이터를 세션에 추가 하는방식대로 , unset_userdata() 는 세션키를 넘겨줌으로써 데이터를 제거 합니다. 예를들어, 'some_name' 을 세션에서 제거하고싶다면:

    $this->session->unset_userdata('some_name');

    이함수는 제거하고자 하는 아이템의 여러개일경우 아래와 같이 연관배열로 넘겨주어 처리할수 있습니다.

    $array_items = array('username' => '', 'email' => '');

    $this->session->unset_userdata($array_items);

    Flashdata

    CodeIgniter는 "flashdata"나 혹은 다음 번 서버요청(server request)에서만 사용가능하며 사용후 자동으로 지워지는 세션데이터를 지원합니다. 이것은 매우 유용하며, 일반적으로 정보성이나 상태표시 메세지에 사용합니다.(예: "record 2 deleted").

    참고: Flash 변수는 "flash_"로 시작하므로 여러분이 직접만든 세션데이터의 키는 이 접두어를 피해주세요.

    flashdata 추가예제:

    $this->session->set_flashdata('item', 'value');

    set_userdata()에서 처럼 set_flashdata() 에 배열을 넘겨줄수 있습니다..

    flashdata 변수 읽기:

    $this->session->flashdata('item');

    만약 추가적인 서버요청후에도 flashdata 변수를 유지하고싶다면 keep_flashdata() 함수를 사용합니다.

    $this->session->keep_flashdata('item');

    세션데이터를 데이터베이스에 저장하기 Saving Session Data to a Database

    세션배열을 데이터베이스에 저장하지않고 세션아이디를 포함하여 사용자의 쿠키에만 저장한다면, 그 세션이 정당한것인지 확인할수 있는 방법이 없습니다. 보안이 필요없는 프로그램에서는 세션아이디 검증이 필요없을수도 있으나, 보안이 필요하다면, 검증은 필수항목이 될것입니다.그렇지 않으면, 사용자가 쿠키를 변조할 경우 그 변조된 쿠키가 재사용될 것입니다.

    세션데이터를 데이터베이스에 저장하면,데이터베이스 쿼리를 통해서 사용자쿠키에 있는 세션아이디와 일치하는 '검증된'세션을 찾을 수 있습니다. 세션아이디가 일치하지않는다면,세션은 파괴됩니다. 세션아이디는 절대로 업데이트될수 없으며, 새로운 세션이 생성될때만 생성될수 있습니다.

    세션을 저장하려면, 그에맞는 데이터베이스 테이블을 생성해야만 합니다 . 아래는 기본 프로토타입입니다( MySQL용) :

    참고: 기본값으로 테이블명은 ci_sessions입니다. 원하는 이름으로 바꾸려면application/config/config.php 파일을 업데이트 하시면됩니다. 테이블이 생성되면 config.php 파일을 아래와 같이 수정하여 , 데이터베이스 옵션을 활성화 시킬수 있습니다:

    $config['sess_use_database'] = TRUE;

    일단 활성화되면, 세션클래스는 데이터를 DB에 저장하게 됩니다.

    config 파일에서 테이블명이 정확히 지정되었는지 확인하세요 :

    $config['sess_table_name'] = 'ci_sessions';

    참고: 세션클래스는 가비지컬렉션기능을 내장하고 있으므로 , 유효기간이 경과한 세션을 제거하기위한 루틴을 별도로 만들 필요가 없습니다.

    세션 제거 Destroying a Session

    현재세션을 제거하려면:

    $this->session->sess_destroy();

    참고: 이함수는 맨 마지막에 호출되어야하며,flash 변수또한 더이상 사용할수 없게됩니다. 몇몇 아이템만 제거하려면 unset_userdata()를 사용하세요.

    세션설정항목 Session Preferences

    application/config/config.php 파일에 아래와같은 세션관련설정들이 있습니다:

    설정 기본값 옵션 설명
    sess_cookie_name ci_session None 저장되는 세션쿠키의 이름입니다.
    sess_expiration 7200 None 세션이 존재할 시간을 초로 지정합니다. 기본값은 2 시간입니다(7200 초). 유효기간을 무한대로 하시려면 0으로 설정하세요.
    sess_expire_on_close FALSE TRUE/FALSE (boolean) 브라우저가 닫힐때 세션이 자동만료 되도록 할것인지 여부.
    sess_encrypt_cookie FALSE TRUE/FALSE (boolean) 세션데이터를 암호화 할것인지 설정합니다.
    sess_use_database FALSE TRUE/FALSE (boolean) 세션데이터를 데이터베이스에 저장할지 설정합니다. 이옵션을 활성화하기전에 반드시 테이블을 생성해두셔야 합니다.
    sess_table_name ci_sessions Any valid SQL table name 세션데이터베이스 테이블의 이름입니다.
    sess_time_to_update 300 Time in seconds 세션이 얼마나자주 재생성되어 새로운 세션아이디를 만들지를 결정합니다.
    sess_match_ip FALSE TRUE/FALSE (boolean) 세션데이터를 읽을때 사용자의 IP주소를 일치시킬지 설정합니다.어떤 ISP들은 IP를 동적으로 변경시킵니다. 그러므로, 유효기간이 무한대인 세션을 만드시려면 이 설정을 FALSE 로 두셔야합니다.
    sess_match_useragent TRUE TRUE/FALSE (boolean) 세션데이터를 읽어들일때 User Agent 를 일치시킬지 설정합니다.
    Migration Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    마이그레이션(Migration) 클래스

    마이그레이션을 통해서 쉽고 안정적으로 데이터베이스를 변경(alter) 할 수 있습니다. 수작업으로 sql을 만들 수도 있지만, 그럴경우 어떤것이 변경되었는지 ,다음 배포때는 어떤것이 수행되어야하는지, 기억하고 있어야 합니다.

    데이터베이스 테이블 마이그레이션은 어떤 마이그레이션이 수행되었는지 지속적으로 추적해 주기 때문에, 개발자는 단지 프로그램 파일을 업데이트 하고 $this->migrate->current() 만 호출하면,배포에 필요한 마이그레이션이 수행됩니다.현재버전은 config/migration.php에 있습니다.

    마이그레이션 생성

    블로그를 포함하고 있는 새 사이트의 첫번째 마이그레이션 일 경우입니다. 모든 마이그레이션은 application/migrations/ 으로 들어가며, 이름은 001_add_blog.php 와 같은 형태가 됩니다.

    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Migration_Add_blog extends CI_Migration {
    
    	public function up()
    	{
    		$this->dbforge->add_field(array(
    			'blog_id' => array(
    				'type' => 'INT',
    				'constraint' => 5,
    				'unsigned' => TRUE,
    				'auto_increment' => TRUE
    			),
    			'blog_title' => array(
    				'type' => 'VARCHAR',
    				'constraint' => '100',
    			),
    			'blog_description' => array(
    				'type' => 'TEXT',
    				'null' => TRUE,
    			),
    		));
    		
    		$this->dbforge->create_table('blog');
    	}
    
    	public function down()
    	{
    		$this->dbforge->drop_table('blog');
    	}
    

    그리고 application/config/migration.php 에서 $config['migration_version'] = 1;으로 설정합니다.

    사용예

    예제에서 사용되는 코드는 application/controllers/migrate.php 에 있으며 스키마를 업데이트 합니다.

    $this->load->library('migration');
    
    if ( ! $this->migration->current())
    {
    	show_error($this->migration->error_string());
    }
    

    함수 레퍼런스

    $this->migration->current()

    application/config/migration.php에 있는 $config['migration_version'] 에 설정된 현재버전

    $this->migration->latest()

    current() 와 거의 유사하게 동작하나, $config['migration_version']를 참조하는 대신, 파일 시스템에 있는 가장 최근의 마이그레이션을 사용합니다.

    $this->migration->version()

    특정버전으로 롤백하거나, 이후 버전으로 바꿀 때 사용합니다. current와 유사하게 동작하나$config['migration_version']를 사용하지 않습니다.

    $this->load->library('migration');
    
    $this->migration->version(5);
    

    마이그레이션 참조

    마이그레이션 설정 옵션

    설정 기본값 옵션 설명
    migration_enabledFALSETRUE / FALSE 마이그레이션 사용/비사용 설정
    migration_version0None 데이터베이스가 사용하고 있는 현재버전
    migration_pathAPPPATH.'migrations/'None 마이그레이션 폴더의 경로
    JavaScript Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    주의: 아직 실험중인 드라이버 입니다. 향후 드라이버 구현내용이 바뀔 수 있습니다.


    Javascript 클래스

    CodeIgniter는Javascript와 함께 사용할 수 있는 일반적인 기능을 제공합니다.CodeIgniter를 실행하기 위해서 jQuery라이브러리가 필요하지는 않습니다. 다른 어떤 스크립트 라이브러리와도 잘 동작합니다. 여기서는 단지 jQuery라이브러리가 편리하다는것을 보여줍니다.

    클래스 초기화

    JavaScript 클래스를 컨트롤러의 생성자에서 수동으로 초기화하려면 $this->load->library 함수를 사용합니다. 현재 자동로드가 가능한 라이브러리는 jQuery뿐이며 다음과 같이 자동으로 로드됩니다.

    $this->load->library('javascript');

    Javascript 클래스에 파라미터를 넘겨줄 수 있습니다.js_library_driver (string) 기본값 'jquery' 그리고 autoload (bool) 기본값TRUE. 연관배열을 넘겨줘서 기본값을 덮어쓸 수 있습니다:

    $this->load->library('javascript', array('js_library_driver' => 'scripto', 'autoload' => FALSE));

    다시말하지만, 현재까지 자동로드로 사용할 수 있는것은 'jquery' 뿐입니다.메인 jquery 파일을 인클루드(include)하는 스크립트 태그가 자동으로 만들어지기를 원하지 않는다면, autoload 를 FALSE로 하세요.jQuery 라이브러리가 Codeigniter 바깥에 있거나, 이미 뷰파일에 jQuery 를 인클루드하는 스크립트가 있을 경우 유용합니다.

    일단 로드되면, jQuery 라이브러리 객체는 다음과 같이 사용할 수 있습니다: $this->javascript

    설치및 설정

    뷰파일에 변수 설정

    자바스크립트 라이브러리 파일들이 프로그램에서 사용가능해야합니다.(역주:당연한 소리를 왜 하는거냐..)

    JavaScript는 클라이언트 사이드 언어이므로 라이브러리는 최종 출력에 포함되어야 됩니다.일반적으로 최종 출력은 뷰이며, 뷰의 <head>안에 다음을 include 해야합니다..

    <?php echo $library_src;?>
    <?php echo $script_head;?>

    $library_src는 실재 라이브러리 파일이나,같이 사용되는 플러그인 들이 로드되는 곳입니다.

    $script_head 에는 이벤트,함수,기타 명령들이 렌더링 되는 위치입니다.

    라이브러리 경로등의 설정

    JavaScript 라이브러리는 몇 가지 설정이 있습니다.각 설정은 설정파일 파일 application/config.php 또는 config/javascript.php에서 하거나, 컨트롤러에서 set_item () 메소드통해서 합니다.

    로더나 진행상황 표시에 이미지를 사용할수 있습니다. 이미지를 지정하지 않으면 ajax 호출시 "loading"이라는 텍스트를 보여줍니다.

    $config['javascript_location'] = 'http://localhost/codeigniter/themes/js/jquery/';
    $config['javascript_ajax_img'] = 'images/ajax-loader.gif';

    위 설정은 파일이 다운로드 될위치와 같은 위치에 파일이 있을경우 적용할 필요가 없습니다.(역주:무슨소린지 잘 모르겠음.. 아래 문장이 원문이니 각자해석바람.)
    If you keep your files in the same directories they were downloaded from, then you need not set this configuration items.

    jQuery 클래스

    jQuery 클래스를 컨트롤러의 생성자에서 수동으로 초기화하려면 다음과 같이$this->load->library 함수를 사용합니다:

    $this->load->library('jquery');

    옵션으로 두번째 파라미터를 FALSE로 설정할 경우, jQuery 를 include 하는 스크립트 태그를 자동으로 만들지 않습니다.(기본값은 자동으로 생성하는 것입니다):

    $this->load->library('jquery', FALSE);

    한 번로드하면 jQuery 라이브러리 객체는 다음과 같이 사용할 수 있습니다 : $this->jquery

    jQuery 이벤트

    이벤트를 추가하려면 아래와같이 하세요.

    $this->jquery->event('element_path', code_to_run());

    위의 예제:

    효과(Effects)

    JQuery 라이브러리는 강력한 효과(effects)들을 지원합니다. 효과를 사용하기전에 반드시 로드하셔야 합니다:

    $this->jquery->effect([optional path] plugin name); // for example $this->jquery->effect('bounce');

    hide() / show()

    항목을 표시하거나 숨김니다. hide ()는 항목을 숨기고, show ()는 그것을 표시합니다.

    $this->jquery->hide(target, optional speed, optional extra information);
    $this->jquery->show(target, optional speed, optional extra information);

    toggle()

    항목의 보이기/숨기기를 전환합니다. 보이는 경우 숨기고 숨어있는 경우 표시합니다.

    $this->jquery->toggle(target);

    animate()

    $this->jquery->animate(target, parameters, optional speed, optional extra information);

    자세한 내용은 다음 링크를 참조하십시오 :http://docs.jquery.com/Effects/animate

    다음은 jQuery의 click()이벤트를 이용하여 id가 "note"인 div에 animate ()를 사용하는 예제입니다..

    $params = array(
    'height' => 80,
    'width' => '50%',
    'marginLeft' => 125
    );
    $this->jquery->click('#trigger', $this->jquery->animate('#note', $params, normal));

    fadeIn() / fadeOut()

    $this->jquery->fadeIn(target, optional speed, optional extra information);
    $this->jquery->fadeOut(target, optional speed, optional extra information);

    toggleClass()

    대상에 대해 CSS 클래스를 추가하거나 제거합니다.

    $this->jquery->toggleClass(target, class)

    fadeIn() / fadeOut()

    대상을 서서히나타게하거나 서서히 사라지게 합니다.

    $this->jquery->fadeIn(target, optional speed, optional extra information);
    $this->jquery->fadeOut(target, optional speed, optional extra information);

    slideUp() / slideDown() / slideToggle()

    요소를 슬라이드시킵니다.

    $this->jquery->slideUp(target, optional speed, optional extra information);
    $this->jquery->slideDown(target, optional speed, optional extra information);
    $this->jquery->slideToggle(target, optional speed, optional extra information);

    플러그인

    본 라이브러리에서 몇가지 jQuery 플러그인이 사용가능 합니다.

    corner()

    대상의 모서리에 다양한 모양을 줄 수 있습니다.. 상세정보 http://www.malsup.com/jquery/corner/

    $this->jquery->corner(target, corner_style);

    $this->jquery->corner("#note", "cool tl br");

    tablesorter()

    나중에 쓸예정임(역주: 번역이 안된게 아니라 원문이 이렇습니다.)

    modal()

    나중에 쓸예정임

    calendar()

    나중에 쓸예정임

    Encryption Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    암호화 Encryption Class

    암호화 클래스는 데이터를 암호화하는 두가지 방법을 제공합니다.본 클래스는 Mcrypt 라이브러리를 사용하여 암호화 하거나, 비트단위의 랜덤해쉬 XOR 인코딩방법(randomly hashed bitwise XOR encoding scheme)을 사용합니다. 만약 서버에서 Mcrypt 라이브러리 사용이 불가능하다면 인코딩된 메세지는 암호화세션이나 혹은 다른 '가벼운'목적에 적절한 수준의 보안을 제공합니다. Mcrypt 라이브러리 사용이 가능하다면 매우 높은 수준의 보안이 제공됩니다.

    키 설정 Setting your Key

    키란 암호화 과정을 컨트롤하고 암호화된 문자열을 다시 복호화 할수 있도록 해주는 작은 정보조각입니다. 사실, 여러분이 선택한 키는 그 키를 사용하여 암호화한 데이터를 복호화할수 있는 유일한 수단이 됩니다. 그러므로 신중히 선택하셔야함은 물론이고 , 영속적인(변하지않는) 데이터에 사용할 경우 키를 변경하지 않으셔아 합니다.

    키를 잘 보호해야한다는것은 말할 필요도 없겠죠 .누군가가 여러분의 키를 손에 넣을수 있다면, 암호화된 데이터는 쉽게 해석되어버릴테니까요. 만약 서버를 여러분이 완전히 통제할수 있는 상황이 아니라면(호스팅을 받고있다든지), 키를 완전히 보호할수 있다고 보장할수 없습니다. 그러므로 , 신용카드 정보라든지 하는 매우 중요한 정보의 암호화를 하기전에 신중히 생각하셔야 합니다.

    암호화 알고리즘의 장점을 최대한 활용하고자한다면 키는 영문기준으로 32글자(128비트)가 되어야하며 문자와 숫자, 대문자와 소문자가 섞인 랜덤 문자열로 하는것이 좋습니다.키를 단순한 문자열로 만들지 마세요 . 가능한한 랜덤하게 만드셔야 합니다.

    키는 application/config/config.php파일에 저장 하거나 혹은 여러분 스스로 만든 저장 매커니즘을 사용하여 동적으로 암호/복호화할때만 전달하도록 할수 있습니다.

    application/config/config.php파일에 저장하려면 해당파일을 여신후 아래와 같이 설정하세요 :

    $config['encryption_key'] = "YOUR KEY";

    메세지 길이 Message Length

    인코딩 된 메시지는 원본 메세지에 비해서 약 2.6배정도 더 길어집니다.예를들어,"my super secret data" 라는 문자열은 21자인데 인코딩 되면 대략 55자가 됩니다.('대략'이라고 표현한 이유는 인코딩시 메세지의 길이는 원본에 정확히 선형적으로 비례하는것이 아니라 64비트 클러스터(64 bit clusters)에 따라 증가하기때문입니다.:we say "roughly" because the encoded string length increments in 64 bit clusters, so it's not exactly linear). 데이터 저장 메커니즘을 선택할때 이러한 사실을 염두에 두셔야합니다. 예를 들어 쿠키의 경우 4K 까지의 정보만을 저장할수 있으니까요.

    클래스 초기화 Initializing the Class

    다른 클래스들과 마찬가지로 , 암호화 클래스도 컨트롤러 클래스에서 $this->load->library 함수를 이용하여 초기화 합니다:

    $this->load->library('encrypt');

    일단 로드되면 암호화 라이브러리 객체는 $this->encrypt 를 통해 사용하실 수있습니다.

    $this->encrypt->encode()

    데이터 암호화를 수행하고 그 결과를 반환합니다.예:

    $msg = 'My secret message';

    $encrypted_string = $this->encrypt->encode($msg);

    만약 config 파일에 정의해두신 키 대신 다른 키를 사용하고자 한다면 옵션으로 두번째 파라미터를 통해 키를 전달할수 있습니다.:

    $msg = 'My secret message';
    $key = 'super-secret-key';

    $encrypted_string = $this->encrypt->encode($msg, $key);

    $this->encrypt->decode()

    암호화 된 문자열을 복호화(해독)합니다. 예:

    $encrypted_string = 'APANtByIGI1BpVXZTJgcsAG8GZl8pdwwa84';

    $plaintext_string = $this->encrypt->decode($encrypted_string);

    설정파일에 있는 암호키대신 다른것을 사용하려면, 두번째 파라미터로 넘기면 됩니다.

    $msg = 'My secret message';
    $key = 'super-secret-key';

    $encrypted_string = $this->encrypt->decode($msg, $key);

    $this->encrypt->set_cipher();

    Mcrypt 해독자(cipher)를 설정할 수 있게 합니다. 기본으로MCRYPT_RIJNDAEL_256가 사용됩니다:

    $this->encrypt->set_cipher(MCRYPT_BLOWFISH);

    Php.net 을 방문하시면 가능한 해독자목록(available ciphers)을 확인하실 수 있습니다.

    서버에서 Mcrypt가 지원되는지 확인하고싶다면 아래의 코드를 사용하세요:

    echo ( ! function_exists('mcrypt_encrypt')) ? 'Nope' : 'Yup';

    $this->encrypt->set_mode();

    Mcrypt 모드를 설정합니다. 기본으로 MCRYPT_MODE_CBC가 사용됩니다. 예:

    $this->encrypt->set_mode(MCRYPT_MODE_CFB);

    Php.net 에서 사용가능한 모드목록( available modes)을 확인하실 수 있습니다.

    $this->encrypt->sha1();

    SHA1 인코딩 함수 입니다. 문자열을 넘겨주면 160 비트의 단방향 해쉬를 리턴합니다. 참고: SHA1은 MD5에서처럼 복호화(decode) 불가능합니다. 예:

    $hash = $this->encrypt->sha1('Some string');

    대부분의 경우 PHP는 SHA1을 기본으로 제공합니다. 만약 해쉬를 인코딩하는것만 필요하다면 php에서 기본제공하는 함수를 사용하는것이 좀더 간단합니다.:

    $hash = sha1('Some string');

    만약 서버에서 SHA1를 지원하지않는다면 위에서 제공하는 함수를 사용하시면됩니다.

    $this->encrypt->encode_from_legacy($orig_data, $legacy_mode = MCRYPT_MODE_ECB, $key = '');

    CodeIgniter 1.x에서 암호화된 데이터를 CodeIgniter 2.x 암호화 클래스와 호환성을 갖도록 다시 인코딩 합니다.파일이나 데이터베이스등에 인코딩된 데이터가 저장된경우, 서버에서 Mcrypt를 지원한다면 이 메서드를 사용할 수 있습니다. 인코딩된 세션이나 임시 데이터등의 경우에 있어서는 개발자가 손댈 부분이 없습니다.하지만,2.x 이전버전에서 인코딩 된 데이터는 디코딩 되지않기 때문에 세션은 제거됩니다.

    왜 구버전의 인코딩, 디코딩을 유지하지 않고 다시 인코딩하는 메서드만 제공하는가? 암호화 클래스의 알고리즘은 CodeIgniter 2.x에서 성능과 안전성 모두 향상되었습니다. 그래서, 이전 방법을 사용하지 않는것이 좋다고 생각했습니다. 암호화 라이브러리를 확장하여 이전버전으로 동작하게 할 수 있겠지만, 신중하게 생각하시기 바랍니다.

    $new_data = $this->encrypt->encode_from_legacy($old_encrypted_string);
    Parameter Default Description
    $orig_data 없음 CodeIgniter 1.x 암호화 클래스에서 암호화된 데이터
    $legacy_mode MCRYPT_MODE_ECB 원래 데이터를 암호화하는 데 사용된 Mcrypt 모드. CodeIgniter 1.x의 기본값은 MCRYPT_MODE_ECB이었으며, 별도로 지정하지않으면 이 값이 사용됩니다.
    $key 없음 암호화 키. 먼저 설명한 것처럼 일반적으로 설정 파일에 지정된 것.
    Output Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    출력 Output Class

    출력클래스는 하나의 주 함수를 가진 작은 클래스 입니다: 브라우저로 최종결과물을 보낼때 사용합니다.또한 웹페이지의 캐싱(caching) 을 사용하신다면 그부분도 담당합니다.

    참고: 이클래스는 시스템에서 자동으로 초기화 됩니다.

    일반적인 상황에서 여러분은 출력클래스의 존재를 알아채지도 못할것입니다. 출력클래스는 여러분의 간섭이 필요하지않으며 투명하게 작동합니다. 예를들어 ,뷰 파일을 로드하기 위해 로더(Loader) 클래스를 사용할때 , 로더는 자동으로 그것을 CI 에서 최종적으로 자동 호출 되는 출력클래스로 전달합니다. 그러나, 필요하면 다음 두 함수를 이용하여 출력클래스를 작동에 여러분이 끼어들수 있습니다:

    $this->output->set_output();

    최종 출력 문자열을 수동으로 설정할수 있도록 해 줍니다. 사용예:

    $this->output->set_output($data);

    중요: 만약 출력을 수동으로 설정한다면, 출력설정을 하는 함수에서 마지막으로 수행하는 작업이 되어야 합니다. 예를들어 , 컨트롤러의 어떤함수에서 페이지를 생성한다면, 반드시 맨 마지막에 출력을 설정하셔야 합니다.

    $this->output->set_content_type();

    JSON 데이터, JPEG's, XML 등을 손쉽게 제공하기 위해서 마임타입을 (mime-type)을 설정합니다.

    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(array('foo' => 'bar')));

    $this->output
        ->set_content_type('jpeg') // You could also use ".jpeg" which will have the full stop removed before looking in config/mimes.php
        ->set_output(file_get_contents('files/something.jpg'));

    주의: config/mimes.php 에 있는 마임타입 외의 것을 설정하면, 작동하지않습니다.

    $this->output->get_output();

    출력 클래스에서 저장을 위해서 전송되는 어떤 내용이라도 뽑아낼수 있게 해줍니다.사용예:

    $string = $this->output->get_output();

    이미 출력클래스로 전송된 데이터만 가져올수 있다는것을 명심하세요 .예를들어 $this->load->view()함수 등을 호출하면 데이터가 출력클래스로 전송된답니다.

    $this->output->append_output();

    출력 문자열에 데이터를 추가합니다. 예:

    $this->output->append_output($data);

    $this->output->set_header();

    서버헤더(server headers)를 설정하는데 사용합니다.예:

    $this->output->set_header("HTTP/1.0 200 OK");
    $this->output->set_header("HTTP/1.1 200 OK");
    $this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_update).' GMT');
    $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
    $this->output->set_header("Cache-Control: post-check=0, pre-check=0");
    $this->output->set_header("Pragma: no-cache");

    $this->output->set_status_header();

    서버상태를 설정하는데 사용합니다 예:

    $this->output->set_status_header('401');
    // Sets the header as: Unauthorized

    여기 를 보시면 헤더 전체 목록이 있습니다.

    $this->output->enable_profiler();

    프로파일러(Profiler)를 활성/비활성 할하는데 사용합니다. 프로파일러는 디버깅이나 프로세스 최적화를위해 벤치마크등의 정보를 페이지 하단에표시 합니다.

    프로파일러를 활성화(enable)하려면 아래코드를 컨트롤러(Controller) 에서 원하는 함수에 추가하시면 됩니다:

    $this->output->enable_profiler(TRUE);

    활성화되면 페이지의 맨 아래에 리포트가 생성됩니다.

    비활성으로 하시려면 아래와 같이 합니다:

    $this->output->enable_profiler(FALSE);

    $this->output->set_profiler_sections();

    프로파일러가 활성화 된 경우 특정 색션을 켜거나 끌수 있습니다. 상세한 정보는프로파일러 페이지에...

    $this->output->cache();

    CodeIgniter 출력라이브러리는 캐시도 컨트롤합니다. 자세한정보는 , 캐싱문서(caching documentation)를 보세요.

    Parsing Execution Variables

    기본값으로, CodeIgniter는 출력 중에 의사 변수 {elapsed_time}{memory_usage} 을 분석합니다. 이것을 비활성화하려면 컨트롤러에서 클래스 속성 $parse_exec_varsFALSE 로 설정합니다.$this->output->parse_exec_vars = FALSE;

    HTML Table Class : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    HTML 테이블

    Table 클래스는 데이터베이스나 배열로 부터 HTML 테이블을 자동으로 생성할 수 있도록 해줍니다.

    클래스 초기화 Initializing the Class

    다른 클래스들 처럼 , Table 클래스도 컨트롤러에서 $this->load->library 함수로 초기화 합니다:

    $this->load->library('table');

    일단 로드되면 , $this->table 을 통해서 테이블 객체를 이용합니다.

    예제 Examples

    이번 예제는 다차원 배열로부터 어떻게 테이블을 만드는지를 보여줍니다. 주의할점은 첫번째 배열인덱스가 테이블의 제목(heading)이 된다는 점입니다. set_heading() 함수를 이용하면 여러분이 직접 제목을 작성하실수도 있습니다.그 방법은 저 아래서 설명합니다.

    $this->load->library('table');

    $data = array(
                 array('Name', 'Color', 'Size'),
                 array('Fred', 'Blue', 'Small'),
                 array('Mary', 'Red', 'Large'),
                 array('John', 'Green', 'Medium')
                 );

    echo $this->table->generate($data);

    이번 예제는 데이터베이스 쿼리결과로 테이블을 만드는것을 보여줍니다.테이블 클래스는 테이블 이름들로부터 제목(heading)을 자동으로 설정합니다. set_heading() 함수를 이용하면 여러분이 직접 제목을 작성하실수도 있습니다.그 방법은 저 아래서 설명합니다.

    $this->load->library('table');

    $query = $this->db->query("SELECT * FROM my_table");

    echo $this->table->generate($query);

    이번 예제는 각각의 파라미터를 이용해서 테이블을 만드는법을 보여줍니다:

    $this->load->library('table');

    $this->table->set_heading('Name', 'Color', 'Size');

    $this->table->add_row('Fred', 'Blue', 'Small');
    $this->table->add_row('Mary', 'Red', 'Large');
    $this->table->add_row('John', 'Green', 'Medium');

    echo $this->table->generate();

    이번예제는 위와 유사하나 개별파라미터가 아닌 배열을 통해 테이블을 만드는법을 보여줍니다:

    $this->load->library('table');

    $this->table->set_heading(array('Name', 'Color', 'Size'));

    $this->table->add_row(array('Fred', 'Blue', 'Small'));
    $this->table->add_row(array('Mary', 'Red', 'Large'));
    $this->table->add_row(array('John', 'Green', 'Medium'));

    echo $this->table->generate();

    테이블 모양 바꾸기 Changing the Look of Your Table

    여러분이 원하는 레이아웃에 맞추어 테이블 템플릿을 설정할 수 있습니다. 아래는 기본적인 테이블 템플릿 설정 예제입니다:

    $tmpl = array (
                        'table_open'          => '<table border="0" cellpadding="4" cellspacing="0">',

                        'heading_row_start'   => '<tr>',
                        'heading_row_end'     => '</tr>',
                        'heading_cell_start'  => '<th>',
                        'heading_cell_end'    => '</th>',

                        'row_start'           => '<tr>',
                        'row_end'             => '</tr>',
                        'cell_start'          => '<td>',
                        'cell_end'            => '</td>',

                        'row_alt_start'       => '<tr>',
                        'row_alt_end'         => '</tr>',
                        'cell_alt_start'      => '<td>',
                        'cell_alt_end'        => '</td>',

                        'table_close'         => '</table>'
                  );

    $this->table->set_template($tmpl);

    참고:  템플릿블록안에는 두 세트의 "row" 블록이 있다는것을 알 수 있습니다. 이렇게하면 한줄(row)마다 반복되는 다른 색 혹은 디자인을 적용할수 있습니다.(예를들어 첫줄 빨간색, 둘째줄 파란색 ,셋째줄 빨간색 , 네째줄 파란색 .......... 이런식 )

    완벽한 구조의 템플릿을 만들필요는 없습니다. 테이블의 일부분만 바꾸고싶다면, 그부분만 템플릿을 만들면 됩니다. 이번예제는 테이블을 여는 태그만 바뀌게 됩니다:

    $tmpl = array ( 'table_open'  => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">' );

    $this->table->set_template($tmpl);

    함수 레퍼런스 Function Reference

    $this->table->generate()

    생성된 테이블을 포함한 문자열을 리턴합니다. 배열이나 데이터베이스 결과 객체를 파라미터로 받습니다.

    $this->table->set_caption()

    테이블의 캡션을 설정합니다.

    $this->table->set_caption('Colors');

    $this->table->set_heading()

    테이블의제목(heading)을 설정합니다. 배열이나 , 각각의 제목을 파라미터로 넘겨줄수 있습니다:

    $this->table->set_heading('Name', 'Color', 'Size'); $this->table->set_heading(array('Name', 'Color', 'Size'));

    $this->table->add_row()

    한줄(row)을 테이블에 추가합니다.배열이나 혹은 각 값을 넘겨줄수 있습니다:

    $this->table->add_row('Blue', 'Red', 'Green'); $this->table->add_row(array('Blue', 'Red', 'Green'));

    각 셀의 태그에 속성을 부여하려면 연관배열을 사용하세요.데이터를 채우려면'data' 키를 사용하시고, 다른 키들은 모두 key='값' 의 형식으로 추가됩니다. :

    $cell = array('data' => 'Blue', 'class' => 'highlight', 'colspan' => 2);
    $this->table->add_row($cell, 'Red', 'Green');

    // generates
    // <td class='highlight' colspan='2'>Blue</td><td>Red</td><td>Green</td>

    $this->table->make_columns()

    이 함수는 1차원 배열을 받아서 원하는 칼럼수에 맞추어 다차원배열을 생성합니다. 이 함수를 통해서 값은 1차원배열인데, 표현하고자하는 칼럼의 개수가 그것보다 작은경우를 효과적으로 처리할수 있습니다.아래 예제를 보시면 이해가 쉬우실거예요:

    $list = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve');

    $new_list = $this->table->make_columns($list, 3);

    $this->table->generate($new_list);

    // Generates a table with this prototype

    <table border="0" cellpadding="4" cellspacing="0">
    <tr>
    <td>one</td><td>two</td><td>three</td>
    </tr><tr>
    <td>four</td><td>five</td><td>six</td>
    </tr><tr>
    <td>seven</td><td>eight</td><td>nine</td>
    </tr><tr>
    <td>ten</td><td>eleven</td><td>twelve</td></tr>
    </table>

    $this->table->set_template()

    여러분이 만든 템플릿을 적용할 수 있도록 해 줍니다. 전체템플릿이나, 부분템플릿을 적용하실 수 있습니다..

    $tmpl = array ( 'table_open'  => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">' );

    $this->table->set_template($tmpl);

    $this->table->set_empty()

    테이블셀의 값이 없을경우 기본값을 설정할수 있습니다.예를들어 아래와같이 한칸의 공백을 표시하는 예약어를 기본값으로 설정할수 있습니다:

    $this->table->set_empty("&nbsp;");

    $this->table->clear()

    테이블을 의 제목과 데이터를 모두 비웁니다. 포함하고 있는 데이터가 다른 여러테이블을 보여줘야할경우 이전 테이블의데이터를 비우는데 사용합니다. 예:

    $this->load->library('table');

    $this->table->set_heading('Name', 'Color', 'Size');
    $this->table->add_row('Fred', 'Blue', 'Small');
    $this->table->add_row('Mary', 'Red', 'Large');
    $this->table->add_row('John', 'Green', 'Medium');

    echo $this->table->generate();

    $this->table->clear();

    $this->table->set_heading('Name', 'Day', 'Delivery');
    $this->table->add_row('Fred', 'Wednesday', 'Express');
    $this->table->add_row('Mary', 'Monday', 'Air');
    $this->table->add_row('John', 'Saturday', 'Overnight');

    echo $this->table->generate();

    $this->table->function

    모든 셀 데이터에 PHP내장함수나 사용가능한 함수배열 객체 (function array object)를 적용합니다

    $this->load->library('table');

    $this->table->set_heading('Name', 'Color', 'Size');
    $this->table->add_row('Fred', '<strong>Blue</strong>', 'Small');

    $this->table->function = 'htmlspecialchars';
    echo $this->table->generate();

    위의 예제에서는 모든 셀 데이터에 PHP의 htmlspecialchars() 함수가 적용되고, 결과는 다음과 같습니다 :

    <td>Fred</td><td>&lt;strong&gt;Blue&lt;/strong&gt;</td><td>Small</td>
    Form Validation : CodeIgniter User Guide

    CodeIgniter User Guide Version 2.1.0


    Form Validation

    Before explaining CodeIgniter's approach to data validation, let's describe the ideal scenario:

    1. A form is displayed.
    2. You fill it in and submit it.
    3. If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data along with an error message describing the problem.
    4. This process continues until you have submitted a valid form.

    On the receiving end, the script must:

    1. Check for required data.
    2. Verify that the data is of the correct type, and meets the correct criteria. (For example, if a username is submitted it must be validated to contain only permitted characters. It must be of a minimum length, and not exceed a maximum length. The username can't be someone else's existing username, or perhaps even a reserved word. Etc.)
    3. Sanitize the data for security.
    4. Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.)
    5. Prep the data for insertion in the database.

    Although there is nothing complex about the above process, it usually requires a significant amount of code, and to display error messages, various control structures are usually placed within the form HTML. Form validation, while simple to create, is generally very messy and tedious to implement.

    CodeIgniter provides a comprehensive validation framework that truly minimizes the amount of code you'll write. It also removes all control structures from your form HTML, permitting it to be clean and free of code.

    Overview

    In order to implement CodeIgniter's form validation you'll need three things:

    1. A View file containing the form.
    2. A View file containing a "success" message to be displayed upon successful submission.
    3. A controller function to receive and process the submitted data.

    Let's create those three things, using a member sign-up form as the example.

    The Form

    Using a text editor, create a form called myform.php. In it, place this code and save it to your applications/views/ folder:

    The Success Page

    Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your applications/views/ folder:

    The Controller

    Using a text editor, create a controller called form.php. In it, place this code and save it to your applications/controllers/ folder:

    Try it!

    To try your form, visit your site using a URL similar to this one:

    example.com/index.php/form/

    If you submit the form you should simply see the form reload. That's because you haven't set up any validation rules yet, which we'll get to in a moment.

    Explanation

    You'll notice several things about the above pages:

    The form (myform.php) is a standard web form with a couple exceptions:

    1. It uses a form helper to create the form opening. Technically, this isn't necessary. You could create the form using standard HTML. However, the benefit of using the helper is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable and flexible in the event your URLs change.
    2. At the top of the form you'll notice the following variable: <?php echo $this->validation->error_string; ?>

      This variable will display any error messages sent back by the validator. If there are no messages it returns nothing.

    The controller (form.php) has one function: index(). This function initializes the validation class and loads the form helper and URL helper used by your view files. It also runs the validation routine. Based on whether the validation was successful it either presents the form or the success page.

    Since you haven't told the validation class to validate anything yet, it returns "false" (boolean false) by default. The run() function only returns "true" if it has successfully applied your rules without any of them failing.

    Setting Validation Rules

    CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. Let's see it in action, we'll explain it afterwards.

    In your controller (form.php), add this code just below the validation initialization function:

    $rules['username'] = "required";
    $rules['password'] = "required";
    $rules['passconf'] = "required";
    $rules['email'] = "required";

    $this->validation->set_rules($rules);

    Your controller should now look like this: