여러 필드와 페이지가 포함된 복잡한 중첩 쿼리를 작성하고 JSON으로 구문 분석할 수 있는 배열을 반환합니다. 이는 SPA 및 PWA에 대한 데이터를 가져오는 데 유용합니다.
모듈을 사용하여 ProcessWire 페이지나 PageArray(심지어 RepeaterMatrixPageArray도 가능)를 배열이나 JSON으로 변환할 수 있습니다. 쿼리는 중첩될 수 있으며 콜백 함수로 클로저를 포함할 수 있습니다. Pageimages 또는 MapMarker와 같은 일부 필드 유형은 자동으로 변환됩니다.
릴리스 페이지를 확인하고 업데이트를 구독하세요.
PageQueryBoss
클래스 이름을 사용하여 ProcessWire 관리자 " 모듈 " > " 사이트 " > " 새로 추가 " > " 디렉토리에서 모듈 추가 "를 통해 설치하는 것이 좋습니다.
Github 또는 ProcessWire 저장소(https://modules.processwire.com/modules/page-query-builder/)에서 파일을 다운로드하세요.
두 가지 주요 방법이 있습니다:
$page->pageQueryJson($query);
$page->pageQueryArray($query);
쿼리에는 키와 값 쌍이 포함될 수도 있고 키만 포함될 수도 있습니다. 중첩될 수 있으며 동적 값에 대한 클로저를 포함할 수 있습니다. 간단한 예를 들면 다음과 같습니다.
// simple query:
$query = [
'height',
'floors',
];
$pages->find('template=skyscraper')->pageQueryJson($query);
쿼리는 중첩될 수 있고 페이지 이름, 템플릿 이름을 포함하거나 함수 및 ProcessWire 선택기를 포함할 수 있습니다.
// simple query:
$query = [
'height',
'floors',
'images', // < some fileds contain default sub-queries to return data
'files' => [ // but you can also overrdide these defaults:
'filename'
'ext',
'url',
],
// Assuming there are child pages with the architec template, or a
// field name with a page relation to architects
'architect' => [ // sub-query
'name',
'email'
],
// queries can contain closure functions
'querytime' => function($parent){
return "Query for $parent->title was built ".time();
}
];
$pages->find('template=skyscraper')->pageQueryJson($query);
단일 필드 이름 ; height
, floors
또는 architects
모듈은 다음 필드를 처리할 수 있습니다.
템플릿 이름 skyscraper
이나 city
하위 페이지 이름 (page.child.name=pagename) my-page-name
ProcessWire 선택기 ; template=building, floors>=25
#
구분 기호로 전달된 반환된 인덱스의 새 이름 :
// the field skyscraper will be renamed to "building":
$query = ["skyscraper`#building`"]
새로운 중첩 하위 쿼리 배열이 있는 위의 키(1-5):
$query = [
'skyscraper' => [
'height',
'floors'
],
'architect' => [
'title',
'email'
],
]
쿼리를 처리하고 반환하기 위한 명명된 키와 클로저 함수입니다 . 클로저는 부모 개체를 인수로 가져옵니다.
$query = [
'architecs' => function($parent)
{
$architects = $parent->find('template=architect');
return $architects->arrayQuery(['name', 'email']);
// or return $architects->explode('name, email');
}
]
$query = [
'title',
'subtitle',
// naming the key invitation
'template=Invitation, limit=1#invitation' => [
'title',
'subtitle',
'body',
],
// returns global speakers and local ones...
'speakers' => function($page){
$speakers = $page->speaker_relation;
$speakers = $speakers->prepend(wire('pages')->find('template=Speaker, global=1, sort=-id'));
// build a query of the speakers with
return $speakers->arrayQuery([
'title#name', // rename title field to name
'subtitle#ministry', // rename subtitle field to ministry
'links' => [
'linklabel#label', // rename linklabel field to minlabelistry
'link'
],
]);
},
// Child Pages with template=Program
'Program' => [
'title',
'summary',
'start' => function($parent){ // calculate the startdate from timetables
return $parent->children->first->date;
},
'end' => function($parent){ // calculate the endate from timetables
return $parent->children->last->date;
},
'Timetable' => [
'date', // date
'timetable#entry'=> [
'time#start', // time
'time_until#end', // time
'subtitle#description', // entry title
],
],
],
// ProcessWire selector, selecting children > name result "location"
'template=Location, limit=1#location' => [
'title#city', // summary title field to city
'body',
'country',
'venue',
'summary#address', // rename summary field to address
'link#tickets', // rename ticket link
'map', // Mapmarker field, automatically transformed
'images',
'infos#categories' => [ // repeater matrix! > rename to categories
'title#name', // rename title field to name
'entries' => [ // nested repeater matrix!
'title',
'body'
]
],
],
];
if ($input->urlSegment1 === 'json') {
header('Content-type: application/json');
echo $page->pageQueryJson($query);
exit();
}
모듈 설정은 공개됩니다. 예를 들어 다음과 같이 직접 수정할 수 있습니다.
$modules->get('PageQueryBoss')->debug = true;
$modules->get('PageQueryBoss')->defaults = []; // reset all defaults
일부 필드 유형 또는 템플릿에는 페이지 이미지 등과 같은 기본 선택기가 제공됩니다. 기본 쿼리는 다음과 같습니다.
// Access and modify default queries: $modules->get('PageQueryBoss')->defaults['queries'] = …
public $defaults = [
'queries' => [
'Pageimage' => [
'basename',
'url',
'httpUrl',
'description',
'ext',
'focus',
],
'Pageimages' => [
'basename',
'url',
'httpUrl',
'description',
'ext',
'focus',
],
'Pagefile' => [
'basename',
'url',
'httpUrl',
'description',
'ext',
'filesize',
'filesizeStr',
'hash',
],
'Pagefiles' => [
'basename',
'url',
'httpUrl',
'description',
'ext',
'filesize',
'filesizeStr',
'hash',
],
'MapMarker' => [
'lat',
'lng',
'zoom',
'address',
],
'User' => [
'name',
'email',
],
],
];
이러한 기본값은 해당 유형에 대해 중첩된 하위 쿼리가 없는 경우에만 사용됩니다. 복잡한 데이터가 포함된 필드를 쿼리하고 하위 쿼리를 제공하지 않으면 그에 따라 변환됩니다.
$page->pageQueryArry(['images']);
// returns something like this
'images' => [
'basename',
'url',
'httpUrl',
'description',
'ext',
'focus'=> [
'top',
'left',
'zoom',
'default',
'str',
]
];
언제든지 자신만의 하위 쿼리를 제공할 수 있으므로 기본값은 사용되지 않습니다.
$page->pageQueryArry([
'images' => [
'filename',
'description'
],
]);
예를 들어 기본값을 재정의할 수도 있습니다.
$modules->get('PageQueryBoss')->defaults['queries']['Pageimages'] = [
'basename',
'url',
'description',
];
중첩된 요소의 색인을 조정할 수 있습니다. 이 작업도 기본값으로 수행됩니다. 3가지 가능성이 있습니다:
이것이 기본 설정입니다. 하위 항목이 포함된 필드가 있는 경우 이름이 결과의 핵심이 됩니다.
// example
$pagesByName = [
'page-1-name' => [
'title' => "Page one title",
'name' => 'page-1-name',
],
'page-2-name' => [
'title' => "Page two title",
'name' => 'page-2-name',
]
]
객체가 $defaults['index-id']에 나열되어 있으면 ID가 결과의 핵심이 됩니다. 현재 ID 기반 인덱스의 기본값으로 나열되는 항목은 없습니다.
$modules->get('PageQueryBoss')->defaults['index-id']['Page'];
// example
$pagesById = [
123 => [
'title' => "Page one title",
'name' => 123,
],
124 => [
'title' => "Page two title",
'name' => 124,
]
]
기본적으로 두 개의 필드는 번호가 매겨진 인덱스를 포함하도록 자동으로 변환됩니다.
// objects or template names that should use numerical indexes for children instead of names
$defaults['index-n'] => [
'skyscraper', // template name
'Pageimage',
'Pagefile',
'RepeaterMatrixPage',
];
// example
$images = [
0 => [
'filename' => "image1.jpg",
],
1 => [
'filename' => "image2.jpg",
]
]
팁: $defaults['index-n']에서 Pageimage
키를 제거하면 색인은 다시 이름 기반이 됩니다.
다음은 여러분이 사용하고 싶거나 시작점으로 도움이 될 수 있는 몇 가지 helpfill 클로저 함수입니다(자신만의 함수가 있으면 알려주십시오).
$query = ['languages' => function($page){
$ar = [];
$l=0;
foreach (wire('languages') as $language) {
// build the json url with segment 1
$ar[$l]['url']= $page->localHttpUrl($language).wire('input')->urlSegment1;
$ar[$l]['name'] = $language->name == 'default' ? 'en' : $language->name;
$ar[$l]['title'] = $language->getLanguageValue($language, 'title');
$ar[$l]['active'] = $language->id == wire('user')->language->id;
$l++;
}
return $ar;
}];
ContinentsAndCountries 모듈을 사용하면 국가의 ISO 코드와 이름을 추출할 수 있습니다.
$query = ['country' => function($page){
$c = wire('modules')->get('ContinentsAndCountries')->findBy('countries', array('name', 'iso', 'code'),['code' =>$page->country]);
return count($c) ? (array) $c[count($c)-1] : null;
}];
RepeaterMatrix를 사용하면 프런트엔드에 대한 템플릿 문자열을 만들 수 있습니다. 이는 버튼, 라벨 등에 유용합니다. 다음 코드는 strings
라는 이름의 반복기를 사용하며 key
와 body
필드가 있고, 반환된 배열에는 키와 body
필드가 값으로 포함되어 있는 key
필드가 포함되어 있습니다.
// build custom translations
$query = ['strings' => function($page){
return array_column($page->get('strings')->each(['key', 'body']), 'body', 'key');
}];
다음 설정을 사용하면 다국어를 처리하고 요청한 언어가 존재하지 않는 경우 기본 언어를 반환할 수 있습니다. URL은 다음과 같이 구성됩니다: page/path/{language}/{content-type}
예: api/icf/zurich/conference/2019/de/json
// get contenttype and language (or default language if not exists)
$lang = wire('languages')->get($input->urlSegment1);
if(!$lang instanceof Nullpage){
$user->language = $lang;
} else {
$lang = $user->language;
}
// contenttype segment 2 or 1 if language not present
$contenttype = $input->urlSegment2 ? $input->urlSegment2 : $input->urlSegment1;
if ($contenttype === 'json') {
header('Content-type: application/json');
echo $page->pageQueryJson($query);
exit();
}
모듈은 wire('config')->debug를 따릅니다. TracyDebug와 통합됩니다. 다음과 같이 재정의할 수 있습니다.
// turns on debug output no mather what:
$modules->get('PageQueryBoss')->debug = true;
백엔드를 통해 기본값을 구성할 수 있도록 합니다. 기본 쿼리를 사용하여 어떻게 스타일 있게 이를 수행할 수 있습니까?
전체 라이선스 텍스트는 포함된 라이선스 파일을 참조하세요.
© noelboss.com