dieschittigs / contao-content-api
通过易于使用的JSON-API访问Contao内容
Requires
- php: ^5.6|^7.0
- contao/core-bundle: ^4.4
Requires (Dev)
- evert/phpdoc-md: ~0.2.0
README
我们Die Schittigs喜爱Contao,但网络在不断发展,静态HTML模板已经不再适用。因此,我们开发了一个易于理解的JSON-API,通过JavaScript(或任何可以处理JSON的东西)访问Contao内容。
使用Contao内容API,您可以完全使用React.js、Angular、vue或其他JS框架编写您的网站前端。同时仍然使用出色的Contao后端。
要求
您需要一个正在运行的 Contao 4.4.x 安装。请注意,该API与 Contao 3.x 不兼容。
安装
如果您还没有安装,请在Contao安装的主目录中输入以下命令安装 composer
composer require dieschittigs/contao-content-api
Contao内容API已安装并准备好使用。
使用方法
安装后,以下路由可用
/api/sitemap
获取包括根页面的网站地图。
/api/sitemap/flat
获取所有页面作为键值对,其中键是URL。
/api/urls[?file=sitemap]
获取由生成的网站地图XML(s)生成的所有URL。如果定义了 file
,则仅解析该XML。
/api/page?url=/about/team.html
获取页面,包括位于 url
的所有文章和内容。
/api/newsreader?url=/news/detail/new-website.html
获取来自 url
的新闻阅读器内容。
/api/?url=/page/or/newsarticle.html
尝试获取 url
上的页面,以及任何阅读器的内容
/api/user
如果存在,获取已登录的前端用户。
/api/module?id=5
通过ID获取模块的内容
/api/text?file=tl_news,modules
通过文件名(s)获取语言文件的内容
/api/file?path=files/uploads&depth=2
获取位于 path
的文件或目录及其子目录,限制由 depth
控制
所有路由还接受额外的 lang
参数(例如,?lang=de
)。如果您需要覆盖语言。
配置
禁用API
编辑您的 parameters.yml
。
parameters:
…
content_api_enabled:
false
…
现在所有API路由都已禁用。如果您只想使用捆绑中包含的类,这可能很有用。
响应头
编辑您的 parameters.yml
。
parameters:
…
content_api_headers:
'Access-Control-Allow-Origin': 'https://mysite.org'
…
以下头将添加到API的所有响应中。
自定义阅读器
Contao有阅读器模块(例如新闻阅读器)的概念。这些可以插入到文章中的任何位置,以读取URL并显示其内容。如果您想添加额外的阅读器模块,您可以通过在 parameters.yml
中添加它们来实现。
parameters:
…
content_api_readers:
newsreader: NewsModel
blogreader: BlogModel
…
请注意,第二个参数是 模型 类,不是模块 类。新的阅读器现在可在以下位置使用
/api/blogreader?url=/blog/detail/on-the-topic.html
或者,如果您想包括整个页面,则在
/api?url=/blog/detail/on-the-topic.html
API 内部尝试使用在 URL 中找到的别名实例化模型。它还尝试添加它找到的所有 ContentModels
。
钩子
我们提供了一些基本的钩子
class Hooks{
// $GLOBALS['TL_HOOKS']['apiBeforeInit']
public static apiBeforeInit(Request $request){
return $request
}
// $GLOBALS['TL_HOOKS']['apiAfterInit']
public static apiAfterInit(Request $request){
return $request
}
// $GLOBALS['TL_HOOKS']['apiContaoJson']
public static apiContaoJson(ContaoJson $contaoJson, mixed $data){
if($data instanceof ContentModel){
$contaoJson->data = null;
// End of the line
return false;
}
// Do your thing, ContaoJson
return true;
}
// $GLOBALS['TL_HOOKS']['apiResponse']
public static apiResponse(mixed $data){
$data->tamperedWith = true;
return $data;
}
// $GLOBALS['TL_HOOKS']['apiModuleGenerated']
public static function apiModuleGenerated(ApiModule $module, string $moduleClass)
{
// Override the way certain modules are handled
if ($moduleClass != 'Contao\ModuleBlogList') {
return;
}
$_module = new ModuleBlogList($module->model, null);
$module->items = $_module->fetchItems(
$module->category
);
}
}
文档
为 API 定制的类可以作为构建 Contao 之上任何内容的好起点。
贡献
欢迎提交错误报告和拉取请求 :)
© Die Schittigs GmbH 2019