CodeIgniter Forums
Creating controller both for CRUD and API REST - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: Creating controller both for CRUD and API REST (/showthread.php?tid=81662)



Creating controller both for CRUD and API REST - kabeza - 04-04-2022

I'm builing 2 controllers
Let's say Project entity

One controller will handle the CRUD, Views, etc.
app\Controllers\Projects.php

PHP Code:
<?php

namespace App\Controllers;

class 
Projects extends BaseController
{
    public function 
index()
    {
    }


The other, will handle the API REST Resources
app\Controllers\api\Project.php

PHP Code:
<?php
namespace App\Controllers;

use 
CodeIgniter\RESTful\ResourceController;

class 
Project extends ResourceController
{
    protected 
$modelName '';
    protected 
$format    'json';
    public function 
index()
    {
    } 

app\Config\Routes.php

Code:
$routes->get('/projects', 'Projects::index');
$routes->resource('/api/project', ['only' => ['index', 'show']]);

When I call the api route with Browser or Postman, I get

ErrorException #64
Cannot declare class App\Controllers\Project, because the name is already in use in D:\www\test\app\Controllers\api\Project.php on line 0

I don't understand it because classNames differ in both Controllers. Any clues? Maybe routes is bad configured?
Thanks for any suggestion


RE: Creating controller both for CRUD and API REST - kenjis - 04-04-2022

The namespace in app\Controllers\api\Project.php is not correct.
PHP Code:
namespace App\Controllers
should be
PHP Code:
namespace App\Controllers\api

But the file path should be app\Controllers\Api\Project.php, and
the namespace also should be App\Controllers\Api,
if you follow the naming convention.


RE: Creating controller both for CRUD and API REST - kabeza - 04-05-2022

Thanks a lot
It worked great