'CodeIgniter'에 해당되는 글 2건

  1. 2010.09.29 CodeIgniter 라이브러리에 ZendAMF 추가하기
  2. 2009.11.26 [CodeIgniter] Multiple Image Upload 1



AMF(Action Message Format
)이란?

-한마디로 말해서 서버와 SWF(플래시)의 통신이 AMF라고 불리는 Binary형식의 프로토콜을 사용하여 이루어지며 서버상에 있는 원격지 객체를 호출합니다.

-가장 작은 패킷 크기에 데이터 통신에 필요한 거의 모든 옵션을 넣을 수 있는 바이너리 메세징 프로토콜

-HTTP(80포트), HTTPS(443)를 통해 통신하기 때문에 방화벽을 무시할 수 있습니다.

-AMF는 플래시 플레이어가 인식 가능한 기본 메세징 포맷이므로 클라이언트에서 데이터 직렬화와 역직렬화가 자동으로 처리되며 속도도 빠릅니다.

-게이트웨이는 HTTP(80포트), HTTPS(443)를 통해 AMF패킷 송수신, AMF직렬화/역직렬화, 적절한 서비스에 요청위임 등을 수행할 수 있는 게이트웨이 라이브러리가 필요합니다. 이러한 게이트웨이 라이브러리 여러 종류 중에 우리는 여기서 ZendAMF라는 것을 사용할 것입니다.


AMF의 구조 :
 http://wiki.gnashdev.org/AMF


Actionscript & PHP Type Mapping

   

PHP to ActionScript mapping

  

PHP

ActionScript

null

null

boolean

boolean

string

string

DomDocument

xml

DateTime

date

float

number

integer

number

Associative Array w/ mix of keys

Object

Associative Array w/ Numeric index of keys

Array

object

object

RemoteClass Zend_Amf_Value_TypedObject

typed object

Zend_Amf_Value_ByteArray

flash.utils.ByteArray

Zend_Amf_Value_ArrayCollection

  

 

원본 위치 <http://framework.zend.com/wiki/display/ZFPROP/Zend_Amf+-+Wade+Arnold>


ZendAMF란?

-Remoting Gateway Library로써 Adobe가 공식지원하여 Zend 프레임워크에서 만들었습니다. AMF3 스펙를 사용하여 AMF0스펙를 사용한 AMFPHP보다 뛰어난 성능을 발휘합니다.    

----------------------------------------------------------------------------------------------------------------------

   

AMF3 스펙 기반으로 만들어진 ZendAMF 라이브러리를 가볍고 막강한 성능을 자랑하는 CI에 추가해보도록 하겠습니다.

   

  1. 준비물:
    1. CodeIgniter (http://codeigniter.com)
    2. ZendAMF (http://framework.zend.com/download/amf)
       
  2. CodeIgniter를 서버에 설치한 후 ZendAMF를 압축해제합니다. 그러면

    이 생성됩니다. 여기서 사용할 것은 library폴더에 들어있는 Zend라는 넘만 쓸 것입니다. Zend폴더를 복사하여
    system>application>libraries>Zend폴더에 넣습니다.

  3. CI의 config파일의 내용변경

    $config['enable_hooks'] = FALSE; --> $config['enable_hooks'] = TRUE;로 변경합니다.

  4. 후킹을 통한 프레임워크 코어확장
    코어파일을 해킹하지 않고도 내부작동방식을 변경하게 하는 기능인 후킹(설명)을 이용하여 컨트롤러가 호출되기 직전(pre-controller)에 실행하게 되게 추가합니다.

    위 hooks.php 파일에 아래 코드를 추가하시면 됩니다.

$hook['pre_controller'][] = array(

  'class' => 'App_hook',

  'function' => 'index',

  'filename' => 'app_hook.php',

  'filepath' => 'hooks'

);


5.    app_hook파일을 hooks폴더에 추가합니다.
 
app_hook.php 파일 안의 코드는

<?php 

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

   

class App_hook

{

    function index()

    {

        ini_set('include_path',ini_get('include_path').PATH_SEPARATOR.BASEPATH.'application/libraries/');

    }

}

?>

이는 기존의 include_path의 값에 appliaction/libraries/를 추가한 것입니다.

6.    Zend 클래스와 다른 프레임워크 클래스를 이용하기 위해 하나의 사용자 라이브러리 파일을 만듭니다.

 

     그 파일 안의 코드는 다음과 같습니다.

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

   

class Apps

{

    function __construct($class NULL)

    {

        if(!empty($class) && is_array($class))

        {

            foreach($class as $item)

            {

                $this->load($item);

            }

        }

    }

      

    function load($class)

    {

        require_once (string) $class EXT;

    }

?>


7.    이제 ZendAMF 라이브러리를 사용할 준비는 끝났습니다. 테스트로 ZendAMF를 로드하는 Remoting Class를 만들어보겠습니다. 여기서 주의하실 점은 폴더명의 대소문자입니다. 이 글의 참고사이트에는 대문자로 되어있어서 그대로 하시면 오류가 생기십니다.
 
        파일을 만드신 후에 안에 코드는 아래와 같습니다.

<?php

class Remote extends Controller 

{

    function Remote()

    {

        parent::Controller();    

    }

      

    function index()

    {

        $this->load->library("Apps");

        $this->apps->load("Zend/Amf/Server"); //여기서 AMF가 아니라 Amf입니다. 각자 다를 수 있으니 확인하세요

          

        $server = new Zend_Amf_Server();

        $server->setClass($this);

        echo $server->handle();

    }

      

    function getData()

    {

        return array(1,2,3,4,5);

    }

?>


8.     Remote클래스를 호출합니다.
 
이라고 뜬다면 성공입니다. 그 외에 폴더명이 잘못되서 에러가 발생할 수 있습니다. 다시 한번 대소문자를 꼭 확인!! 

   

  
 
참고사이트

http://codeigniter.com/wiki/AMF_Flash_Remoting_with_Zend_and_CI/
http://www.cyworld.com/duck_info/3856801
http://framework.zend.com/wiki/display/ZFPROP/Zend_Amf+-+Wade+Arnold

Posted by Finebe
,


여러개의 이미지 업로드할 수 있는 소스입니다.
참고사이트는
http://codeigniter.com/forums/viewthread/80610/
http://codeigniter.com/forums/viewthread/129011/

Controller

 
class Upload extends Controller {

    function Upload()
    {
        parent::Controller();
        $this->load->helper(array('form','url','file'));
        
    
    }
    
    function index()
    {
        
        $this->load->view('upload/upload_index'); //Upload Form
        
    }

    function picupload()
    {
        //Load Model
        $this->load->model('Process_image');

        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size']    = '2048'; //2 meg


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

        foreach($_FILES as $key => $value)
        {
            if( ! empty($key['name']))
            {
                $this->upload->initialize($config);
        
                if ( ! $this->upload->do_upload($key))
                {
                    $errors[] = $this->upload->display_errors();
                    
                }    
                else
                {

                    $this->Process_image->process_pic();

                }
             }
        
        }
        
        
        $data['success'] = 'Thank You, Files Upladed!';

        $this->load->view('upload/upload_pictures', $data); //Picture Upload View

        
        
        
    } 


Model
class Process_image extends Model {
    
    function Process_image()
    {
        parent::Model();
        
        $this->load->library('image_lib');
        //Generate random Activation code
        
        function generate_code($length = 10){
    
                if ($length <= 0)
                {
                    return false;
                }
            
                $code = "";
                $chars = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
                srand((double)microtime() * 1000000);
                for ($i = 0; $i < $length; $i++)
                {
                    $code = $code . substr($chars, rand() % strlen($chars), 1);
                }
                return $code;
            
                }

    }

function process_pic()
    {   
        //Connect to database
        $this->load->database();
        
        //Get File Data Info
        $uploads = array($this->upload->data());
        
        $this->load->library('image_lib');

        //Move Files To User Folder
        foreach($uploads as $key[] => $value)
        {
            
                        //Gen Random code for new file name
            $randomcode = generate_code(12);
            
            $newimagename = $randomcode.$value['file_ext'];
            
            //Creat Thumbnail
            $config['image_library'] = 'GD2';
            $config['source_image'] = $value['full_path'];
            $config['create_thumb'] = TRUE;
            $config['thumb_marker'] = '_tn';
            $config['master_dim'] = 'width';
            $config['quality'] = 75;
            $config['maintain_ratio'] = TRUE;
            $config['width'] = 175;
            $config['height'] = 175;
            $config['new_image'] = '/pictures/'.$newimagename;

            //$this->image_lib->clear();
            $this->image_lib->initialize($config);
            //$this->load->library('image_lib', $config);
            $this->image_lib->resize();
            
            //Move Uploaded Files with NEW Random name
            rename($value['full_path'],'/pictures/'.$newimagename);
            
            //Make Some Variables for Database
            $imagename = $newimagename;
            $thumbnail = $randomcode.'_tn'.$value['file_ext'];
            $filesize = $value['file_size'];
            $width = $value['image_width'];
            $height = $value['image_height'];
            $timestamp = time();
            
            //Add Pic Info To Database
            $this->db->set('imagename', $imagename);
            $this->db->set('thumbnail', $thumbnail);
            $this->db->set('filesize', $filesize);
            $this->db->set('width', $width);
            $this->db->set('height', $height);
            $this->db->set('timestamp', $timestamp);
            
            //Insert Info Into Database
            $this->db->insert('pictures');

        }
        
        
        
    }


View


Table
CREATE TABLE IF NOT EXISTS `img_pictures` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `imagename` varchar(100) NOT NULL,
  `thumbnail` varchar(100) DEFAULT NULL,
  `folder` varchar(255) DEFAULT NULL,
  `filesize` int(11) NOT NULL,
  `width` int(11) NOT NULL,
  `height` int(11) NOT NULL,
  `thumb_width` int(11) DEFAULT NULL,
  `thumb_height` int(11) DEFAULT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8; 
Posted by Finebe
,