레이블이 codeigniter인 게시물을 표시합니다. 모든 게시물 표시
레이블이 codeigniter인 게시물을 표시합니다. 모든 게시물 표시

2007/08/23

CodeIgniter 에서 객체를 수동으로 생성해서 사용하기

CodeIgniter 에서는 라이브러리나 컨트롤을 읽어들일때 자동으로 클래스를 할당하게 되므로 실제로 배열에 객체 데이터를 담을 수 없다.
 
이때 다음과 같은 파일을 만들고 쓰면 잘 된다.
 
application/system/libraries 디렉토리 밑에 beans.php 파일을 아래와 같이 만든다.
 
<pre>
&lt;?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class beans
{
    /**
     * 빈즈 이름
     *
     * @var string
     */
    var $beans_name;
   
    /**
     * 빈즈 파일을 읽어들일 기본 경로
     *
     * @var string
     */
    var $load_dir;
   
    function beans ( $dir )
    {
        // 기본적으로 Beans 를 불러들일 경로
        $this->load_dir = APPPATH . 'libraries/' . $dir . '/';
    }
   
    function load ( $beans_name )
    {
        // 불러들일 Beans 파일 포함
        include_once ( $this->load_dir . $beans_name . EXT );
    }
}
?>
</pre>
 
이 때 Beans 를 불러오는 기본 경로는 다르게 설정해주는 것이 좋다. 본인은 libraries 밑에 beans 파일을 두기로 했다.
 
그리고 다음과 같이 컨트롤러나 라이브러리에서 사용해주면 된다.
 
$this->load->library ( 'beans', 'warning' );
$this->beans->load ( 'test' );
$tester = new test ();
 
여기서는 본인이 test 라고 만든 빈즈 파일을 시험삼아 해보았으니 필요에 따라 만들면 되겠다..

2007/08/14

CodeIgniter 에서 PEAR 라이브러리 사용하기

CodeIgniter 는 단 시간내에 빠른 개발 방법을 지원하는 경량급 PHP 프레임워크인데, 모든 것을 이 안에서 다 제공하다 보니 하나의 문제가 생겼다. 바로 외부에 존재하는 수 많은 라이브러리의 사용이 그것이다.

이 글은 PHP 에서 지원하는 PEAR 라이브러리를 CodeIgniter 에서 사용하는 방법을 다룬다.

CodeIgniter 에서 Pear 를 사용하기 위해선 6 가지의 절차를 거쳐야 한다.

우선 config/config.php 파일을 열어서 아래처럼 바꿔준다.

$config['enable_hooks'] = FALSE; ☞ $config['enable_hooks'] = TRUE

그리고 같은 디렉토리 아래 hooks.php 파일을 열어 파일의 맨 끝(PHP 선언이 끝나기 전에 있는 라인)에 다음 내용을 추가해준다.


$hook['pre_controller'][] = array (
'class' => 'Pear_hook',
'function' => 'index',
'filename' => 'pear_hook.php',
'filepath' => 'hooks'
);


이제 hook 을 작성할 차례이다. application 아래에 hooks 디렉토리로 이동해 다음 이름으로 파일을 작성한다.

파일 이름 : pear_hook.php

<?php if ( !defined ( 'BASEPATH' )) exit ( 'No direct script access allowed' );
class Pear_hook
{
function index ()
{
// on Apache
// ini_set ( 'include_path', ini_get ( 'include_path' ) . ':' . BASEPATH . 'application/web/pear/' );
ini_set ( 'include_path', ini_get ( 'include_path' ) . ':' . BASEPATH . 'application/web/pear/' );
}
}
?>


여기까지 따라왔으니 이제 3단계만 더 거치면 PEAR 를 원활하게 사용할 수 있다. application/libraries 디렉토리로 이동해 아래 파일을 작성한다.

파일 이름 : Pearloader.php

<?php if ( !defined ( 'BASEPATH' )) exit ( 'No direct script access allowed' );
class PearLoader
{
function load ( $package, $class, $options = null )
{
require_once ( $package . '/' . $class . '.php' );
if ( strpos ( $package, '/' ) ) $package = str_replace ( '/', '_', $package );
$classname = $package . "_" . $class;
if ( is_null ( $options ) )
{
return new $classname ();
}
else
{
return new $classname ( $options );
}
}
}
?>


여기까지가 CodeIgniter 에서 Pear 라이브러리를 사용하기 위해 준비를 한 것이다. 이제 최종 단계가 2단계 남아있는데, 따라하자.

하나는 실제 사용할 PEAR 라이브러리와 PEAR.php 파일의 복사가 필요하다.

PEAR.php 파일은 PEAR 가 설치된 경로에 가면 있으니 application 디렉토리 아래 pear 라는 디렉토리를 만들어 복사하고, 실제 사용할 PEAR 라이브러리는 pear.php 에서 받아서 pear 디렉토리 아래에 넣어두면 된다.

이때 사용할 PEAR 라이브러리의 디렉토리명과 클래스명을 잘 파악해둬야 한다(물론 사용하기 위해 불러들이는 파일 하나만에 대해서다).

내 경우 Spreadsheet_Excel_Writer 라는 클래스를 사용해야 하는데, pearloader.php 에서 클래스를 동적으로 할당할 경우 다음과 같이 넘기면

$this->pearloader->load ( 'Spreadsheet/Excel', 'Writer' );

파일은 제대로 포함하지만 클래스는 할당되지 못한다. 이런 경우를 위해 pearloader 클래스에서 동적 클래스 할당전에 약간의 트릭을 사용해서 동적할당이 가능하게 하였다.

사용할 PEAR 라이브러리를 모두 위치했다면 이제 사용할 차례이다.

PEAR 라이브러리를 사용할 Controller 나 Model 등에서 다음과 같이 사용한다.

$this->load->library ( 'pearloader' );
$http_request = $this->pearloader->load('HTTP','Request');
$http_request->setURL($url);
$http_request->sendRequest();
echo $http_request->getResponseBody();

끝.. 헉헉.. 글 쓰기 힘들다. CodeIgniter 를 제대로 활용하기 위한 것도 꽤 힘들다..

Codeigniter 에서 세션 사용하기

CodeIgniter 에서 제대로 세션이 동작되지 않는 경우가 있다.

난 비록 얼마 사용하지 않았지만.. 이번에 좀 큰 시스템을 개발 중인데 이같은 문제가 발생해 난감해 하던차에 구글을 뒤져 다음과 같은 코드로 바꿔치기 하면 된다는 사실을 알았다.

단 이때 코드는 system/libraries 에 있는 Session.php 를 다른 이름으로 바꾸고 그 다음에 아래 내용을 Session.php 로 저장해서 넣으면 된다.

즐거운 CodeIgniter 생활이 되기를..


<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Code Igniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* @package CodeIgniter
* @author Dariusz Debowczyk
* @copyright Copyright (c) 2006, D.Debowczyk
* @license http://www.codeignitor.com/user_guide/license.html
* @link http://www.codeigniter.com
* @since Version 1.0
* @filesource
*/

// ------------------------------------------------------------------------

/**
* Session class using native PHP session features and hardened against session fixation.
*
* @package CodeIgniter
* @subpackage Libraries
* @category Sessions
* @author Dariusz Debowczyk
* @link http://www.codeigniter.com/user_guide/libraries/sessions.html
*/
class CI_Session {

var $flash_key = 'flash'; // prefix for "flash" variables (eg. flash:new:message)

function CI_Session()
{
$this->object =& get_instance();
log_message('debug', "Native_session Class Initialized");
$this->_sess_run();
}

/**
* Regenerates session id
*/
function regenerate_id()
{
// copy old session data, including its id
$old_session_id = session_id();
$old_session_data = $_SESSION;

// regenerate session id and store it
session_regenerate_id();
$new_session_id = session_id();

// switch to the old session and destroy its storage
session_id($old_session_id);
session_destroy();

// switch back to the new session id and send the cookie
session_id($new_session_id);
session_start();

// restore the old session data into the new session
$_SESSION = $old_session_data;

// update the session creation time
$_SESSION['regenerated'] = time();

// session_write_close() patch based on this thread
// http://www.codeigniter.com/forums/viewthread/1624/
// there is a question mark ?? as to side affects

// end the current session and store session data.
session_write_close();
}

/**
* Destroys the session and erases session storage
*/
function destroy()
{
unset($_SESSION);
if ( isset( $_COOKIE[session_name()] ) )
{
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
}

/**
* Reads given session attribute value
*/
function userdata($item)
{
if($item == 'session_id'){ //added for backward-compatibility
return session_id();
}else{
return ( ! isset($_SESSION[$item])) ? false : $_SESSION[$item];
}
}

/**
* Sets session attributes to the given values
*/
function set_userdata($newdata = array(), $newval = '')
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}

if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$_SESSION[$key] = $val;
}
}
}

/**
* Erases given session attributes
*/
function unset_userdata($newdata = array())
{
if (is_string($newdata))
{
$newdata = array($newdata => '');
}

if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
unset($_SESSION[$key]);
}
}
}

/**
* Starts up the session system for current request
*/
function _sess_run()
{
session_start();

$session_id_ttl = $this->object->config->item('sess_expiration');

if (is_numeric($session_id_ttl))
{
if ($session_id_ttl > 0)
{
$this->session_id_ttl = $this->object->config->item('sess_expiration');
}
else
{
$this->session_id_ttl = (60*60*24*365*2);
}
}

// check if session id needs regeneration
if ( $this->_session_id_expired() )
{
// regenerate session id (session data stays the
// same, but old session storage is destroyed)
$this->regenerate_id();
}

// delete old flashdata (from last request)
$this->_flashdata_sweep();

// mark all new flashdata as old (data will be deleted before next request)
$this->_flashdata_mark();
}

/**
* Checks if session has expired
*/
function _session_id_expired()
{
if ( !isset( $_SESSION['regenerated'] ) )
{
$_SESSION['regenerated'] = time();
return false;
}

$expiry_time = time() - $this->session_id_ttl;

if ( $_SESSION['regenerated'] <= $expiry_time )
{
return true;
}

return false;
}

/**
* Sets "flash" data which will be available only in next request (then it will
* be deleted from session). You can use it to implement "Save succeeded" messages
* after redirect.
*/
function set_flashdata($key, $value)
{
$flash_key = $this->flash_key.':new:'.$key;
$this->set_userdata($flash_key, $value);
}

/**
* Keeps existing "flash" data available to next request.
*/
function keep_flashdata($key)
{
$old_flash_key = $this->flash_key.':old:'.$key;
$value = $this->userdata($old_flash_key);

$new_flash_key = $this->flash_key.':new:'.$key;
$this->set_userdata($new_flash_key, $value);
}

/**
* Returns "flash" data for the given key.
*/
function flashdata($key)
{
$flash_key = $this->flash_key.':old:'.$key;
return $this->userdata($flash_key);
}

/**
* PRIVATE: Internal method - marks "flash" session attributes as 'old'
*/
function _flashdata_mark()
{
foreach ($_SESSION as $name => $value)
{
$parts = explode(':new:', $name);
if (is_array($parts) && count($parts) == 2)
{
$new_name = $this->flash_key.':old:'.$parts[1];
$this->set_userdata($new_name, $value);
$this->unset_userdata($name);
}
}
}

/**
* PRIVATE: Internal method - removes "flash" session marked as 'old'
*/
function _flashdata_sweep()
{
foreach ($_SESSION as $name => $value)
{
$parts = explode(':old:', $name);
if (is_array($parts) && count($parts) == 2 && $parts[0] == $this->flash_key)
{
$this->unset_userdata($name);
}
}
}
}
?>

codeigniter library 에서 객체 사용하기

codeigniter 의 library 를 사용자가 임의로 생성할 때 Controller나 Model, View 처럼 모든 상속된 객체를 생성할 순 없게 되어 있다.

따라서 library 에선 다음과 같이 codeigniter 의 모든 객체를 사용할 수 있도록 해주어야 한다.

$obj =& get_instance ();

위와 같이 하면 Controller 나 Model 등에서 다음과 같이 사용하는 것처럼 할 수 있다.

Controller:

$this->session->userdata ( 'id' );

Library:

$obj->session->userdata ( 'id' );

위처럼 사용하면 된다. 다만 library 의 모든 메소드에서 객체를 사용하는 것일 경우 객체의 변수에 담아 다음과 같이 사용할 수 있는 방법도 있겠다.

$this->obj =& get_instance ();

$this->obj->session->userdata ( 'id' );

나머진 취향에^^

codeigniter 에서 Library 폴더를 서브 폴더로 구성해서 사용하기

개인적으로 codeigniter 를 능숙하게 쓰는건 아니지만 조금 큰 규모의 사이트를 제작하다 보니 서브 폴더를 사용해야 했다. 나중에 알고본 사실이지만 다른 문제도 발생했었다^^;
그건 다시 적기로 하고 글을 이어나간다.

controller 에서 library 를 로드할때 다음과 같이 서브 폴더를 포함해 읽어들이도록 하면 에러가 발생한다.

$this->load->library ( 'member/libmember' );

때문에 좀 큰 규모의 설정을 바꿔줘야 한다.

codeigniter 가 설치된 디렉토리에서 다음과 같은 경로를 따라간다.

system/libraries

이 안에 들어가서 Loader.php 를 열고 679 번째 줄을 찾아 다음 내용을 삽입한다.


// Is the class in a sub-folder? If so, parse out the filename and path.
if (strpos($class, '/') === FALSE)
{
$path2 = '';

}
else
{
$x = explode('/', $class);

$class = end($x);

unset($x[count($x)-1]);

$path2 = implode('/', $x).'/';

}


그리고 나서 다음 내용을 아래와 같이 수정한다.

수정전 :

// Is this a class extension request?
if (file_exists(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT))
{
if ( ! file_exists(BASEPATH.'libraries/'.ucfirst($class).EXT))
{
log_message('error', "Unable to load the requested class: ".$class);
show_error("Unable to load the requested class: ".$class);
}

include(BASEPATH.'libraries/'.ucfirst($class).EXT);
include(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT);

return $this->_ci_init_class($class, config_item('subclass_prefix'), $params);
}


수정후 :

// Is this a class extension request?
if (file_exists(APPPATH.'libraries/'.$path2.config_item('subclass_prefix').$class.EXT))
{
if ( ! file_exists(BASEPATH.'libraries/'.$path2.ucfirst($class).EXT))
{
log_message('error', "Unable to load the requested class: ".$class);
show_error("Unable to load the requested class: ".$class);
}

include(BASEPATH.'libraries/'.$path2.ucfirst($class).EXT);
include(APPPATH.'libraries/'.$path2.config_item('subclass_prefix').$class.EXT);

return $this->_ci_init_class($class, config_item('subclass_prefix'), $params);
}


그리고 다음 줄을 찾아서 수정후로 바꿔준다.

수정전 :

$fp = $path.'libraries/'.$class.EXT;

수정후 :

$fp = $path.'libraries/'.$path2.$class.EXT;

이렇게 해주면 다음과 같이 가능하다.

libraries/member/libmember.php 파일이 있다면

라이브러리 로드시에 다음과 같이 사용해도 에러가 나지 않는다.

$this->load->library ( 'member/libmember' );

만약 위처럼 수정하지 않는다면 라이브러리는 서브폴더를 사용하지 못하게 된다.