Search code examples
phpwordpresswordpress-rest-api

WordPress: Error while importing Trait inside Class


I'm using WordPress rest api, and I have created a custom theme, and I want to code using OOP. And I'm having issues importing a Trait inside a Class.

here is the code:

MyController class

<?php

namespace Controllers;

use Controllers\RespondsWithHttpStatus;

class MyController {
  use RespondsWithHttpStatus;

  public function __construct() {}

  public function hello() {
    return "hello world";
  }

}

RespondsWithHttpStatus trait

<?php

namespace Controllers;

trait RespondsWithHttpStatus
{

    protected function success($message, $data = [], $status = 200)
    {
        return array([
            'success' => true,
            'data' => $data,
            'message' => $message,
            'timestamp' => current_time( 'timestamp', 1)
        ], $status);
    }


    protected function failure($message, $status = 422)
    {
        return array([
            'success' => false,
            'message' => $message,
            'timestamp' => current_time( 'timestamp', 1)
        ], $status);
    }

}

functions.php

<?php

require_once('Controllers/MyController.php';

add_action('rest_api_init', 'greet');

 function greet() {
    register_rest_route('greet/v1', 'greet', array(
        'methods' => WP_REST_SERVER::READABLE,
        'callback' => 'greeting'
    ));
 }

 function greeting() {
     $myController = new MyController();
     return $myController->hello();
 }

What is causing the problem is "use RespondsWithHttpStatus" field in MyController Class, I have tried to use namespaces and use keyword, but without luck.


Solution

  • Using require_once('RespondsWithHttpStatus.php'); in MyController.php solved the issue.