Create a Controller
Controllers define the logic for handling requests in WNCMS. Depending on your use case, you’ll extend one of WNCMS’s built-in base controllers for the correct context.
Choosing the right base
| Use case | Extend from | Namespace | View / Response |
|---|---|---|---|
| Backend (admin CRUD pages) | Wncms\Http\Controllers\Backend\BackendController | App\Http\Controllers\Backend | backend.{model_plural}.* |
| Frontend (theme pages) | Wncms\Http\Controllers\Frontend\FrontendController | App\Http\Controllers\Frontend | frontend.theme.{theme}.* |
| API (JSON endpoints) | Wncms\Http\Controllers\Api\V1\ApiController | App\Http\Controllers\Api\V1 | JSON responses |
| Custom base (rare) | Wncms\Http\Controllers\Controller | App\Http\Controllers | Choose any |
Avoid extending the base
Controllerdirectly unless you’re creating a new controller layer or a specialized abstraction.
Example: Backend controller
php
namespace App\Http\Controllers\Backend;
use Illuminate\Http\Request;
use Wncms\Http\Controllers\Backend\BackendController;
class PostController extends BackendController
{
public function index(Request $request)
{
$query = $this->modelClass::query();
if ($keyword = $request->get('keyword')) {
$query->where('title', 'like', "%{$keyword}%");
}
$posts = $query->orderByDesc('id')->paginate(20);
return $this->view("backend.{$this->plural}.index", [
'page_title' => __('wncms::word.model_management', ['model_name' => __('wncms::word.' . $this->singular)]),
'posts' => $posts,
]);
}
}Example: Frontend controller
php
namespace App\Http\Controllers\Frontend;
use Wncms\Http\Controllers\Frontend\FrontendController;
class PageController extends FrontendController
{
public function show(string $slug)
{
$page = wncms()->getModelClass('page')::where('slug', $slug)->first();
abort_unless($page, 404);
return $this->view("frontend.theme.{$this->theme}.pages.show", compact('page'));
}
}Example: API controller
php
namespace App\Http\Controllers\Api\V1;
use Illuminate\Http\Request;
use Wncms\Http\Controllers\Api\V1\ApiController;
class LinkController extends ApiController
{
public function index(Request $request)
{
$links = wncms()->link()->getList([
'status' => 'active',
'page_size' => (int) $request->input('page_size', 20),
]);
return response()->json([
'status' => 'success',
'data' => $links,
]);
}
}Naming and routes
Use plural route prefixes (e.g.
posts,links).Match route names with plural convention (
posts.index,links.edit,frontend.links.single).Register in the correct route file:
routes/backend.phpfor backend controllers.routes/frontend.phpfor frontend controllers.routes/api.phpfor API controllers.
Summary
- Decide context — backend, frontend, or API.
- Extend the appropriate base controller.
- Follow naming conventions for route names and view folders.
- Use WNCMS helpers such as
wncms()->getModelClass(),wncms()->cache(), andwncms()->view(). - Keep controllers thin — move business logic into Managers or Resources when possible.