LoginSignup
27
28

More than 5 years have passed since last update.

Phalcon(PHP Framwork)::APIスケルトン

Posted at

Phalcon

Phalcon Frameworkを利用してAPIを実装したときのスケルトンを紹介します。

本家ドキュメントでは、

http://docs.phalconphp.com/en/latest/reference/micro.html

を参考にしました。

ディレクトリ・ファイル構成

基本構成は、Phalcon Developer Toolsを使用して作成しました。

phalcon-micro
│  .htaccess
│  app.php
│
├─.phalcon
├─app
│  ├─collections
│  │      UserCollection.php
│  │
│  ├─config
│  │      config.php
│  │      loader.php
│  │      services.php
│  │
│  ├─controllers
│  │      ControllerBase.php
│  │      UserController.php
│  │
│  ├─models
│  └─views
│
├─logs
│
└─public
    │  .htaccess
    │  index.php
    │
    ├─css
    ├─files
    ├─img
    └─js

API用に追加した部分

  1. コントローラー

    Developer Toolsで作成すると、MVしかない。

  2. コレクション

    http://docs.phalconphp.com/en/latest/reference/micro.html#using-controllers-as-handlers

サンプルソース

app.php

※ルーターの役割

<?php

//APIのバージョン
$version = "1.0";

//未定義のパスにアクセスした場合に実行される
$app->notFound(array(new ControllerBase(), "notFoundAction"));

//コレクションのインクルード
include __DIR__ . '/app/collections/UserCollection.php';

UserCollection.php
<?php

use Phalcon\Mvc\Micro\Collection as MicroCollection;

$userCollection = new MicroCollection();

//メインコントローラー
$userCollection->setHandler(new UserController());

//コレクション内での共通prefix
$userCollection->setPrefix("/{$version}/user");

/**
  * ユーザー情報取得
  *
  * http://api.sample.com/1.0/user/
  * に対して
  * GETでアクセスすると
  * UserControllerのapi_indexメソッドが実行される
  */
$userCollection->get("/", "api_index");

/**
  * ユーザー登録
  *
  * http://api.sample.com/1.0/user/register/
  * に対して
  * POSTでアクセスすると
  * UserControllerのapi_registerメソッドが実行される
  */
$userCollection->post("/register", "api_register");

$app->mount($userCollection);

UserController.php
<?php

class UserController extends ControllerBase {

    public function api_index() {

    }

    public function api_register() {

    }
}
ControllerBase.php

※全てのコントローラーのベース

<?php

use Phalcon\Mvc\Controller;

class ControllerBase extends Controller
{
    /**
     * 
     * @param int $code
     * @param array $content
     */
    protected function output($code, $content=array()) {
        //Header
        $this->response->setContentType('application/json')
                       ->setStatusCode($code, null)
                       ->sendHeaders();
        //Body
        $this->response->setJsonContent($content)
                       ->send();
    }

    public function notFoundAction() {
        $this->output(404);
    }
}
27
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
28