October/Winter CMS创建组件component
OctoberCMS有个非常重要的概念就是Component(组件),和ReactJS、VueJS等前端框架中的Componet概念一样,Component的出现让开发变得模块化,更简单且易维护,前面介绍过用创建Widget,今天来创建一个可设置数据调用数量及排序方式的Componet。
先看效果图
文件目录结构
Component的存放目录位于对应插件下的components
目录,components需要分别需要一个业务逻辑处理的php
文件和一个数据展现的htm
文件,后者同样使用twig
模板语法
注册Component
打开插件目录下的Plugin.php
文件(本文示例目录: /Plugins/Julian/Library/Plugin.php
),找到registerComponents()
,添加
return [ 'Julian\Library\Components\Awards' => 'awards' ];
业务逻辑 awards.php
创建文件 /Plugins/Julian/Library/Components/Awards.php
<?php namespace Julian\Library\Components; use Cms\Classes\ComponentBase; use Julian\Library\Models\Award; class Awards extends ComponentBase{ public function componentDetails(){ return [ 'name' => 'Award list', 'description' => 'List of awards' ]; } //自定义组件配置项 public function defineProperties(){ return [ 'results' => [ 'title' => 'Number of Awards', 'description' => 'How many awards do you want to display?', 'default' => 0, 'validationPattern' => '^[0-9]+$', 'validationMessage' => 'Only numbers allowed' ], 'sortOrder' => [ 'title' => 'Sort Awards', 'description' => 'Sort those awards', 'type' => 'dropdown', 'default' => 'award_title asc' ] ]; } //设置排序方式 public function getSortOrderOptions(){ return [ 'award_title asc' => 'Name (Ascending)', 'award_title desc' => 'Name (Descending)' ]; } public function onRun(){ $this->awards = $this->loadAwards(); } //数据处理 protected function loadAwards(){ $query = Award::all(); if($this->property('sortOrder') == 'award_title asc'){ $query = $query->sortBy('award_title'); } if($this->property('sortOrder') == 'award_title desc'){ $query = $query->sortByDesc('award_title'); } if($this->property('results') > 0){ $query = Award::all()->take($this->property('results')); } return $query; } public $awards; } ?>
数据展示 default.htm
创建文件 /Plugins/Julian/Library/Components/Awards/default.htm
{% set awards = __SELF__.awards %} <ul> {% for award in awards %} <li>{{ award.award_title }}</li> {% endfor %} </ul>