dispatch

a tiny library for quick and easy PHP 5.6+ apps

Github星跟踪图

dispatch

  • a tiny library for quick and easy PHP apps
  • requires PHP 5.6+

Here's a sample of how you'd usually use dispatch.

<?php

require 'path/to/dispatch.php';

# sample JSON end point
route('GET', '/books.json', function ($db, $config) {
  $list = loadAllBooks($db);
  $json = json_encode($list);
  return response($json, 200, ['content-type' => 'application/json']);
});

# html end point
route('GET', '/books/:id', function ($args, $db) {
  $book = loadBookById($db, $args['id']);
  $html = phtml(__DIR__.'/views/book', ['book' => $book]);
  return response($html);
});

# respond using a template
route('GET', '/about', page(__DIR__.'/views/about'));

# sample dependencies
$config = require __DIR__.'/config.php';
$db = createDBConnection($config['db']);

# arguments you pass here get forwarded to the route actions
dispatch($db, $config);

If you want to see where all the state goes, you can use action and serve.

<?php

require 'path/to/dispatch.php';

# create a stack of actions
$routes = [
  action('GET', '/books.json', function ($db, $config) {
    $list = loadAllBooks($db);
    $json = json_encode($list);
    return response($json, 200, ['content-type' => 'application/json']);
  }),
  action('GET', '/books/:id', function ($args, $db) {
    $book = loadBookById($db, $args['id']);
    $html = phtml(__DIR__.'/views/book', ['book' => $book]);
    return response($html);
  }),
  action('GET', '/about', page(__DIR__.'/views/about'))
];

# sample dependencies
$config = require __DIR__.'/config.php';
$db = createDBConnection($config['db']);

# we need the method and requested path
$verb = $_SERVER['REQUEST_METHOD'],
$path = $_SERVER['REQUEST_URI'],

# serve app against verb + path, pass dependencies
$responder = serve($routes, $verb, $path, $db, $config);

# invoke responder to flush response
$responder();

tests

Tests for dispatch use plain assertions.

php tests/dispatch-tests.php

If no errors were printed, then you're all good.

license

MIT

主要指标

概览
名称与所有者noodlehaus/dispatch
主编程语言PHP
编程语言PHP (语言数: 1)
平台
许可证
所有者活动
创建于2012-02-01 05:37:06
推送于2025-01-19 05:16:03
最后一次提交2025-01-19 13:16:02
发布数101
最新版本名称11.0.1 (发布于 2023-04-11 20:46:39)
第一版名称1.0.0 (发布于 2013-06-04 01:21:26)
用户参与
星数534
关注者数47
派生数103
提交数486
已启用问题?
问题数46
打开的问题数0
拉请求数51
打开的拉请求数0
关闭的拉请求数10
项目设置
已启用Wiki?
已存档?
是复刻?
已锁定?
是镜像?
是私有?