Welcome Guest, Not a member yet? Register   Sign In
Controller or its method is not found: \\App\\Controllers\\Home::index
#1

(This post was last modified: 02-27-2022, 05:09 AM by spreaderman.)

This is such a beginner problem but I just cannot figure it out.  Trying to build a simple api.

Here is my controller for creating an employee...

PHP Code:
<?php
namespace App\Controllers\Api\v1;
use 
CodeIgniter\RESTful\ResourceController;
use 
App\Models\EmployeeModel;

class 
EmployeeController extends ResourceController
{

    public function create_employee()
    {
        $rules = [ 
            'employee_name'    => 'required|max_length[100]',
            'employee_email'    => 'required|is_unique[employees.employee_email]|min_length[5]|max_length[100]'
        ];
        
        
if (!$this->validate($rules))
        {
            $response = [
                'status'    => 500,
                'message'  => $this->validator->getErrors(),
                'error'    => true,
                'data'      => []
            ];
            
        
} else {
            $file $this->request->getFile('employee_profile_image');
            
            
if (!empty($file)){
                // if employee_profile_image exists, create a new file name and upload it.
                $employee_profile_image_name $file->getName();
                $old_employee_profile_image_name explode('.'$employee_profile_image_name);
                $new_employee_profile_image_name round(microtime(true)).'.'.end($old_employee_profile_image_name);
                if ($file->move('user_public/images'$new_employee_profile_image_name)){
                    // need to add error handling
                    $employee_profile_image '/user_public/images/'.$new_employee_profile_image_name;
                }else{
                    // failed to upload
                    $response = [
                        'status'    => 500,
                        'message'  => 'Failed to Upload Image',
                        'error'    => true,
                        'data'      => []
                    ];
                }
            } else {
                // if employee_profile_image doesnt exist, set a standard non image.
                $employee_profile_image =  '/user_public/images/noimage-760x460.png'
            }
        
            $employees_object 
= new EmployeeModel();
            $employee_data = [
                'employee_name' => $this->request->getVar('employee_name'),
                'employee_email' => $this->request->getVar('employee_email'),
                'employee_profile_image' => $employee_profile_image
            
];
            
            
if ($employees_object->insert($employee_data)){
                // success
                $response = [
                    'status'    => 200,
                    'message'  => 'Employee Created',
                    'error'    => false,
                    'data'      => []
                ];
            } else {
                // failed
                $response = [
                    'status'    => 500,
                    'message'  => 'Failed to Create Employee',
                    'error'    => true,
                    'data'      => []
                ];
            }  
        
}
        return $this->respondCreated($response);    
    
}



The error is;

Code:
<b>Fatal error</b>:  Cannot declare class App\Controllers\Api\v1\EmployeeController, because the name is already in use in <b>/var/www/example.com/api.example.com/app_dir/app/Controllers/Api/v1/EmployeeController.php</b> on line <b>0</b><br />
{
    "title": "ErrorException",
    "type": "ErrorException",
    "code": 500,
    "message": "Cannot declare class App\\Controllers\\Api\\v1\\EmployeeController, because the name is already in use",
    "file": "/var/www/example.com/api.example.com/app_dir/app/Controllers/Api/v1/EmployeeController.php",
    "line": 0,
    "trace": [
        {
            "function": "shutdownHandler",
            "class": "CodeIgniter\\Debug\\Exceptions",
            "type": "->"
        }
    ]
}

I am using POSTMAN.  There is no line 0.  How is it possible to debug this?  I have looked everywhere but I don't see a duplicate.

Also, here is my route;

PHP Code:
$routes->group('api', function($routes){

    $routes->post('create-employee''/Api/v1/EmployeeController::create_employee');

}); 
Reply
#2

1. Use a backslash in the namespace of the route.
2. Do not use a backslash at the beginning of a route namespace name if that namespace is part of the default namespace.
Reply
#3

(02-27-2022, 06:54 AM)iRedds Wrote: 1. Use a backslash in the namespace of the route.
2. Do not use a backslash at the beginning of a route namespace name if that namespace is part of the default namespace.

I read that / slash work but will fail on variable route.

Anyway, I tried below;

$routes->post('create-employee', '/Api/v1/EmployeeController::create_employee');
$routes->post('create-employee', 'Api/v1/EmployeeController::create_employee');
$routes->post('create-employee', '\Api\v1\EmployeeController::create_employee');
$routes->post('create-employee', 'Api\v1\EmployeeController::create_employee');

and receive the same error.

Any other idea?
Reply
#4

I cannot reproduce.

app/Controllers/Api/v1/EmployeeController.php:
PHP Code:
<?php

namespace App\Controllers\Api\v1;

use 
CodeIgniter\RESTful\ResourceController;

class 
EmployeeController extends ResourceController
{
    public function create_employee()
    {
        return 'Okay';
    }


PHP Code:
$routes->group('api', function($routes){
    $routes->post('create-employee''Api\v1\EmployeeController::create_employee');
}); 

I see "Okay".
Reply
#5

(This post was last modified: 02-27-2022, 08:18 PM by spreaderman. Edit Reason: making pretty )

PHP Code:
$routes->group('api', function($routes){
    $routes->post('create-test''Api\v1\EmployeeController::create_test');
}); 


PHP Code:
namespace App\Controllers\Api\v1;
use 
CodeIgniter\RESTful\ResourceController;
class 
EmployeeController extends ResourceController
{  
    
public function create_test(){
        return "okay";
    }



Above produces below if accessed from URL: https://api.example.com/api/create-test and POSTMAN (verb POST)

    404 - File Not Found
    Create-test is not a valid controller name

My directory structure is;

 
Code:
  app/Controllers/Api/v1/EmployeeController.php

If I change the verb to GET, I get "okay".  Same with POSTMAN.

PHP Code:
$routes->group('api', function($routes){
    $routes->get('create-test''Api\v1\EmployeeController::create_test');


I have had this problem many weeks so appreciate your help!
Reply
#6

What if you don't use POSTMAN to send the POST request?
Reply
#7

(02-27-2022, 08:54 PM)kenjis Wrote: What if you don't use POSTMAN to send the POST request?

You mean construct a form and post to that controller? Thank you.
Reply
#8

(This post was last modified: 03-01-2022, 08:57 PM by spreaderman.)

With this code, I can get a reply "okay".

PHP Code:
public function testmethod(){
        
 helper
(['curl']);
 
 
$rest_api_base_url 'https://api.example.com';
 
 
$get_endpoint '/api/create-test';
 
 
$response $this->perform_http_request('POST'$rest_api_base_url $get_endpoint);
 
 
print_r($response);
    
 
    function perform_http_request($method$url$data false) {
        $curl curl_init();
    
        
switch ($method) {
            case "POST":
                curl_setopt($curlCURLOPT_POST1);
    
                
if ($data) {
                    curl_setopt($curlCURLOPT_POSTFIELDS$data);
    }
    
                
break;
            case "PUT":
                curl_setopt($curlCURLOPT_PUT1);
    
                
break;
            default:
                if ($data) {
                    $url sprintf("%s?%s"$urlhttp_build_query($data));
    }
        }
    
        curl_setopt
($curlCURLOPT_URL$url);
        curl_setopt($curlCURLOPT_RETURNTRANSFER1);
        curl_setopt($curlCURLOPT_SSL_VERIFYPEERfalse); //If SSL Certificate Not Available, for example, I am calling from http://localhost URL
    
        $result 
curl_exec($curl);
    
        curl_close
($curl);
    
        
return $result;
    

The above code mainly came from https://roytuts.com/codeigniter-4-consum...rest-apis/ and is not mine.
Reply
#9

It seems POSTMAN does not send correct  POST request.

And you can create a form easily like this:

PHP Code:
<?php
namespace App\Controllers\Api\v1;
use 
App\Controllers\BaseController;
class 
EmployeeController extends BaseController
{
    public function index()
    {
        return <<<'HTML'
            <form action="/api/create-test" method="post" accept-charset="utf-8">
            <input type="submit" name="submit" value="Submit">
            </form>
            HTML;
    }

    public function create_test()
    {
        return "okay";
    }

Reply
#10

(This post was last modified: 03-07-2022, 12:41 AM by spreaderman.)

Unfortunately, I still am not understanding fully. 

For example, here is my controller;

PHP Code:
<?php
namespace App\Controllers\Api\v1;
use 
CodeIgniter\RESTful\ResourceController;
use 
App\Models\UserModel;
use 
App\Entities\UserEntity;

class 
User extends ResourceController
{

    public function __construct(){
 
$this->UserModel = new \App\Models\UserModel;
 }
    
    
public function index(){
  
      $data 
$this->UserModel->orderBy('id''DESC')->findAll();
      return $this->respond($data);
    }


If I access http://www.example.com/Api/v1/User or Api/v1/User/index I get an error Controller or its method is not found: \App\Controllers\Api\V1::User

If I add a route as follows;  $routes->get('/users', 'Api\v1\User::index');

and then access http://www.example.com/users, it works and I get a json list of users. 

Why is this?
Reply




Theme © iAndrew 2016 - Forum software by © MyBB