쇼핑카트(Shopping Cart Class)

쇼핑카트 클래스는 유저가 사이트를 이용하는 동안 아이템들이 세션에 추가되어 유효한 상태를 유지하도록 해줍니다. 세션에 추가된 아이템들은 장바구니 형식으로 검색되거나 출력될 수 있고, 유저가 장바구니에서 아이템의 수량을 고치거나 삭제할 수 있도록 해줍니다.

Important

쇼핑카트 클래스는 DEPRECATED 되었습니다. 사용하시면 안됩니다. 이전 버전과의 호환 때문에 유지되고 있습니다.

장바구니 클래스는 오직 장바구니의 핵심 기능들만을 제공하므로, 배송, 신용카드 승인, 또는 다른 처리 컴포넌트들은 제공하지 않습니다.

쇼핑카트 클래스 사용하기 Using the Cart Class

클래스 초기화 Initializing the Shopping Cart Class

Important

장바구니 클래스는 장바구니 정보를 데이타베이스에 저장하기 위해 CodeIgniter의 세션 클래스를 사용합니다. 그러므로 장바구니 클래스를 사용하기 전에 세션 문서에 제시되어 있는 것 처럼 데이타베이스 테이블을 설정해야 합니다. 그리고 데이타베이스를 사용하기 위해 application/config/config.php 파일 안에있는 세션 환경설정을 설정합니다.

컨트롤러에서 장바구니 클래스를 초기화하기 위해 $this->load->library() 함수를 사용합니다:

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

장바구니 클래스가 로드되면, cart 객체를 사용할 수 있게 됩니다:

$this->cart

Note

장바구니 클래스는 자동으로 세션클래스를 로드하고 초기화합니다. 그러므로 세션을 다른 곳에서 사용하지 않는 이상, 세션 클래스를 로드 할 필요는 없습니다.

카트에 아이템 추가 Adding an Item to The Cart

장바구니에 아이템을 추가하려면, 아래와 같이 상품 정보가 담긴 배열을 $this->cart->insert() 으로 넘기면 됩니다:

$data = array(
        'id'      => 'sku_123ABC',
        'qty'     => 1,
        'price'   => 39.95,
        'name'    => 'T-Shirt',
        'options' => array('Size' => 'L', 'Color' => 'Red')
);

$this->cart->insert($data);

Important

위의 배열에서 처음 4개의 인덱스들 (id, qty, price, name)은 필수입니다. 저것들 중에 하나라도 빠질경우, 데이타는 장바구니에 저장되지 않습니다. 다섯번째 인덱스인 (options)는 선택사항 입니다. 다섯번째 인덱스는 상품이 추가 옵션을 가질 경우 사용될 수 있도록 되어있습니다. 위에 보이는 것처럼 options는 배열을 사용합니다.

다섯개의 정해진 인덱스:

  • id - 각각의 상품은 고유번호를 가져야 합니다. 이것은 보통 SKU 또는 고유번호가 됩니다.
  • qty - 구입될 수량입니다.
  • price - 상품의 가격입니다.
  • name - 상품의 이름 입니다.
  • options - 상품을 식별할 추가적인 정보입니다. 이것들은 배열을 통해서 전달되어야 합니다.

위에 있는 다섯개의 인덱스 말고도 2개의 정해진 인덱스 rowid and subtotal가 있습니다. 이것들은 장바구니 클래스 내부에서 사용되므로 장바구니에 데이타를 추가할 때 이 단어들을 인덱스로 사용해서는 안됩니다.

배열은 추가적인 데이타 포함 할 수 있습니다. 배열에 포함된 모든 것은 무엇이든지 세션에 저장됩니다. 그렇지만, 좀 더 쉽게 상품들을 테이블에 출력하기 위해서 데이타를 형식에 맞춰 통일시키면 좋습니다.

$data = array(
        'id'      => 'sku_123ABC',
        'qty'     => 1,
        'price'   => 39.95,
        'name'    => 'T-Shirt',
        'coupon'         => 'XMAS-50OFF'
);

$this->cart->insert($data);

insert() 함수로 아이템을 입력에 성공하면 $rowid 가 리턴됩니다.

다량의 아이템들을 장바구니에 추가 Adding Multiple Items to The Cart

아래처럼 다중배열을 사용하여 여러 개의 아이템을 한 번에 장바구니로 추가하는 것이 가능합니다. 이것은 같은 페이지 안에 있는 여러 상품들 중에 사용자가 선택할 수 있도록 할 때 편리합니다.

$data = array(
        array(
                'id'      => 'sku_123ABC',
                'qty'     => 1,
                'price'   => 39.95,
                'name'    => 'T-Shirt',
                'options' => array('Size' => 'L', 'Color' => 'Red')
        ),
        array(
                'id'      => 'sku_567ZYX',
                'qty'     => 1,
                'price'   => 9.95,
                'name'    => 'Coffee Mug'
        ),
        array(
                'id'      => 'sku_965QRS',
                'qty'     => 1,
                'price'   => 29.95,
                'name'    => 'Shot Glass'
        )
);

$this->cart->insert($data);

장바구니 출력 Displaying the Cart

장바구니를 출력하려면 아래에 보이는 코드와 비슷하게 뷰파일(view file)을 만듭니다.

이 예제는 폼 헬퍼 (form helper)를 사용 한다는 점을 주의해주세요.

<?php echo form_open('path/to/controller/update/method'); ?>

<table cellpadding="6" cellspacing="1" style="width:100%" border="0">

<tr>
        <th>QTY</th>
        <th>Item Description</th>
        <th style="text-align:right">Item Price</th>
        <th style="text-align:right">Sub-Total</th>
</tr>

<?php $i = 1; ?>

<?php foreach ($this->cart->contents() as $items): ?>

        <?php echo form_hidden($i.'[rowid]', $items['rowid']); ?>

        <tr>
                <td><?php echo form_input(array('name' => $i.'[qty]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?></td>
                <td>
                        <?php echo $items['name']; ?>

                        <?php if ($this->cart->has_options($items['rowid']) == TRUE): ?>

                                <p>
                                        <?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>

                                                <strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br />

                                        <?php endforeach; ?>
                                </p>

                        <?php endif; ?>

                </td>
                <td style="text-align:right"><?php echo $this->cart->format_number($items['price']); ?></td>
                <td style="text-align:right">$<?php echo $this->cart->format_number($items['subtotal']); ?></td>
        </tr>

<?php $i++; ?>

<?php endforeach; ?>

<tr>
        <td colspan="2"> </td>
        <td class="right"><strong>Total</strong></td>
        <td class="right">$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
</tr>

</table>

<p><?php echo form_submit('', 'Update your Cart'); ?></p>

장바구니 업데이트 Updating The Cart

장바구니에 있는 정보를 업데이트 하려면 Row ID 와 수량이 들어간 배열을 $this->cart->update() 에 전달하면 됩니다.

Note

만약 수량이 0 으로 지정된다면, 아이템은 장바구니에서 삭제됩니다.

$data = array(
        'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
        'qty'   => 3
);

$this->cart->update($data);

// Or a multi-dimensional array

$data = array(
        array(
                'rowid'   => 'b99ccdf16028f015540f341130b6d8ec',
                'qty'     => 3
        ),
        array(
                'rowid'   => 'xw82g9q3r495893iajdh473990rikw23',
                'qty'     => 4
        ),
        array(
                'rowid'   => 'fh4kdkkkaoe30njgoe92rkdkkobec333',
                'qty'     => 2
        )
);

$this->cart->update($data);

당신은 또한 당신이 이전에 정의한 모든 속성을 업데이트 할 수 있습니다.

$data = array(
        'rowid'  => 'b99ccdf16028f015540f341130b6d8ec',
        'qty'    => 1,
        'price'  => 49.95,
        'coupon' => NULL
);

$this->cart->update($data);

Row ID 가 무엇인가 What is a Row ID?

row ID는 아이템이 장바구니에 추가될 때 장바구니 코드에 의해 생성되는 유니크한 식별자 입니다. 유니크한 ID가 생성되는 이유는 다른 옵션의 똑같은 상품들이 장바구니에 의해 관리될 수 있기 때문입니다.

예를 들어, 어떤 사람이 2장의 각각 다른 사이즈의 똑같은 티셔츠(같은 상품 ID)를 산다고 합시다. 두 개의 티셔츠는 똑같은 티셔츠이므로 상품 ID (그리고 다른 옵션들)는 같습니다. 2장의 티셔츠의 다른점은 사이즈 뿐입니다. 이렇게 두 개의 셔츠가 따로 관리되어야 하기 때문에 장바구니는 서로 다른 식별자를 가져야 합니다. 여기서 두장의 티셔츠는 상품ID를 기반으로 유니크한 "row ID"를 가짐으로서 따로 관리될 수 있고 어떠한 옵션하고도 연결될 수 있습니다.

거의 대부분, 장바구니를 업데이트 하는 것은 "장바구니 보기" 페이지를 통해 사용자가 하는 것입니다. 개발자 입장에서는, "장바구니 보기" 페이지의 히든 폼 필드에 이 정보를 가지고 있고 폼이 섭밋 될 때 그 정보가 업데이트 함수으로 잘 전달 되도록 만드는 것 말고는 "rod ID"에 대해서 염려하지 않아도 됩니다. 더 많은 정보를 위해서는 위에 있는 "장바구니 보기" 페이지 구조를 검토해주세요.

클래스 레퍼런스

class CI_Cart
$product_id_rules = '.a-z0-9_-'

These are the regular expression rules that we use to validate the product ID - alpha-numeric, dashes, underscores, or periods by default

$product_name_rules = 'w -.:'

These are the regular expression rules that we use to validate the product ID and product name - alpha-numeric, dashes, underscores, colons or periods by default

$product_name_safe = TRUE

Whether or not to only allow safe product names. Default TRUE.

insert([$items = array()])
인수:
  • $items (array) – Items to insert into the cart
반환값:

TRUE on success, FALSE on failure

반환형:

bool

Insert items into the cart and save it to the session table. Returns TRUE on success and FALSE on failure.

update([$items = array()])
인수:
  • $items (array) – Items to update in the cart
반환값:

TRUE on success, FALSE on failure

반환형:

bool

This method permits changing the properties of a given item. Typically it is called from the “view cart” page if a user makes changes to the quantity before checkout. That array must contain the rowid for each item.

remove($rowid)
인수:
  • $rowid (int) – ID of the item to remove from the cart
반환값:

TRUE on success, FALSE on failure

반환형:

bool

Allows you to remove an item from the shopping cart by passing it the $rowid.

total()
반환값:Total amount
반환형:int

Displays the total amount in the cart.

total_items()
반환값:Total amount of items in the cart
반환형:int

Displays the total number of items in the cart.

contents([$newest_first = FALSE])
인수:
  • $newest_first (bool) – Whether to order the array with newest items first
반환값:

An array of cart contents

반환형:

array

Returns an array containing everything in the cart. You can sort the order by which the array is returned by passing it TRUE where the contents will be sorted from newest to oldest, otherwise it is sorted from oldest to newest.

get_item($row_id)
인수:
  • $row_id (int) – Row ID to retrieve
반환값:

Array of item data

반환형:

array

Returns an array containing data for the item matching the specified row ID, or FALSE if no such item exists.

has_options($row_id = '')
인수:
  • $row_id (int) – Row ID to inspect
반환값:

TRUE if options exist, FALSE otherwise

반환형:

bool

Returns TRUE (boolean) if a particular row in the cart contains options. This method is designed to be used in a loop with contents(), since you must pass the rowid to this method, as shown in the Displaying the Cart example above.

product_options([$row_id = ''])
인수:
  • $row_id (int) – Row ID
반환값:

Array of product options

반환형:

array

Returns an array of options for a particular product. This method is designed to be used in a loop with contents(), since you must pass the rowid to this method, as shown in the Displaying the Cart example above.

destroy()
반환형:void

장바구니를 Destroy 하도록 허용합니다. 당신이 고객의 주문 처리를 완료할 때 이 함수는 호출될 수 있습니다.