I’m using rainlab blog plugin and would like to use the plugins/rainlab/blog/components/Posts.php component logic within my own plugin’s API controller
In my plugin:
<?php
namespace MyPlugin\Api\Controllers;
class BlogAPIController extends Controller
{
public function getPostList(): JsonResponse
{
// use rainlab.blog.components.posts to load blog posts - howto?
// can we extend the rainlab Posts component and add a method getPosts() to return
// the posts list (and use it here)?
}
}
Any help much appreciated, can’t seem to find this on google
use RainLab\Blog\Components\Posts;
class BlogAPIControler extends Controller
{
public function getPostList(): JsonResponse
{
$postsComponent = new Posts;
// You may have to set some properties on the component here
$posts = $postsComponent->listPosts();
}
}
However you might be better off using the listFrontEnd() scope that’s on the Post model instead.
use RainLab\Blog\Models\Post;
class BlogAPIControler extends Controller
{
public function getPostList(): JsonResponse
{
/**
* Define your options array for the scope
*/
$options = [
'page' => '',
'perPage' => '',
'sort' => '',
'categories' => '',
'exceptCategories' => '',
'category' => '',
'search' => '',
'published' => '',
'exceptPos' => '',
];
$posts = Post::listFrontEnd($options)->get();
}
}
Very cool (this scope thing is new to me! I can call Post::listFrontEnd even though the method isn’t called that ). Thanks @ncarps, seems to be working great