Skip to content

CHICPRO

  • Life Log
  • Cycling Log
  • Photo Log
    • Portrait
    • Landscape
    • Flower
    • Etc
  • Coding Log
  • Information

[PHP] Slimframework를 이용한 영카트5 상품정보 API 서버 구성

2017-09-01 by 편리

Slimframework(이하 Slim)를 이용한 RESTfull API 서버를 구성해보기 위해  영카트5의 상품정보를 제공하는 API 서버를 테스트했다. Slim은 이제 접하는 것이기 때문에 제대로 한 것인지는 확신이 없지만.. 일단 작동은 잘 되는 듯 하다. DB 관련 부분 때문에 코드가 길어졌는데 이 부분은 추후 어떻게 되지 않을까? 싶다. Slim설치 때는 composer를 사용한다.

우선 디렉토리 구성은 아래와 같다.

├── adm
│   ├── css
│   ├── img
│   ├── shop_admin
│   │   └── img
│   └── sms_admin
│       ├── css
│       └── img
├── api
│   └── vendor

api 디렉토리 안에서 아래 명령어로 Slim을 설치했다.

$ composer require slim/slim "^3.0"

Slim 설치가 완료된 후 api 디렉토리 안에 아래의 파일들을 생성한다.

config.php

<?php
$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;

dbconfig.php

<?php
define('G5_SHOP_TABLE_PREFIX', 'g5_shop_');

$config['db']['host']   = 'localhost';
$config['db']['user']   = 'user';
$config['db']['pass']   = 'password';
$config['db']['dbname'] = 'db';

$config['db']['table'] = array(
    'item_table' => G5_SHOP_TABLE_PREFIX.'item'
);

DB 접속 정보는 각자 환경에 맞게 수정한다.

index.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require './vendor/autoload.php';
require './config.php';
require './dbconfig.php';

$app = new \Slim\App(["settings" => $config]);

$container = $app->getContainer();

$container['db'] = function ($c) {
    $db = $c['settings']['db'];
    
    $mysqli = new mysqli($db['host'], $db['user'], $db['pass'], $db['dbname']);
    if($mysqli->connect_errno) {
        echo 'Connect Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
    }

    $mysqli->set_charset("utf8");
    
    return $mysqli;
};

$app->get('/item/{code}', function (Request $request, Response $response) {
    $code = trim($request->getAttribute('code'));

    $_tables = $this->settings['db']['table'];

    $sql = " select it_id, it_name, ca_id, ca_id2, ca_id3, it_explan, it_img1 from `{$_tables['item_table']}` where it_id = ? ";

    $stmt = $this->db->stmt_init();
    $stmt->prepare($sql);
    $stmt->bind_param('s', $code);
    $stmt->execute();

    $row = array();
    $result = array();
    $meta = $stmt->result_metadata();
 
    while ($field = $meta->fetch_field()) {
        $params[] = &$row[$field->name];
    }
 
    call_user_func_array(array($stmt, 'bind_result'), $params);
 
    while ($stmt->fetch()) {
        foreach($row as $key => $val)
        {
            $c[$key] = $val;
        }

        $result = $c;
    }

    $stmt->close();

    return $response->withJson($result);
});

$app->run();

상품정보는 json 형식으로 제공한다. 테스트 :  http://yc5.codepub.net/api/item/1486802989

테스트와 같은 url로 접속 때 요청을 처리하기 위해 nginx 설정에 아래의 설정을 추가했다.

location /api/ {
    try_files $uri /api/index.php$is_args$args;

    location ~ \.php {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index index.php;
        fastcgi_pass  unix:/var/run/fpm-default.sock;
    }
}

직접 코딩을 했다면 제법 오랜 시간이 걸렸을 것 같은데.. Slim을 사용해서 생각보다 빨리 작업이 끝났다. API 서버를 구축할 일이 생기면 PHP로 Slim을 먼저 고려해볼 듯 하다.

Post navigation

Previous Post:

chrome headless 모드를 이용하여 랜더링된 html 소스 가져오기 #2

Next Post:

[PHP] Slack 채널로 메세지 전송

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

  • SK 세븐모바일 유심 셀프교체
  • php 배열 연산에서 + 와 array_merge 의 차이
  • pcntl_fork 를 이용한 다중 프로세스 실행
  • 아이폰 단축어를 이용하여 주중 공휴일엔 알람 울리지 않게 하기
  • 구글 캘린더 전체일정 재동기화
  • OpenLiteSpeed 웹서버에 HTTP 인증 적용
  • OpenLiteSpeed 웹어드민 도메인 연결
  • WireGuard를 이용한 VPN 환경 구축
  • Ubuntu 22.04 서버에 OpenLiteSpeed 웹서버 세팅
  • 맥 vim 세팅

Recent Comments

  • 편리 on 업무관리용 그누보드 게시판 스킨
  • 임종섭 on 업무관리용 그누보드 게시판 스킨
  • 캐논 5D 펌웨어 | Dslr 펌웨어 업그레이드 방법 82 개의 베스트 답변 on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • Top 5 캐논 5D 펌웨어 Top 89 Best Answers on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • 편리 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 임팀장 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 편리 on Notepad++ NppFTP 플러그인 수동 설치
  • paul-j on Notepad++ NppFTP 플러그인 수동 설치
  • YS on Windows 10 iCloud 사진 저장 폴더 변경
  • 편리 on Docker를 이용한 Centos7 + httpd + php 5.4 개발환경 구축

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
© 2025 CHICPRO | Built using WordPress and SuperbThemes