1

I have this code in native php app.

 use Elasticsearch\ClientBuilder;
 require 'vendor/autoload.php';

I am converting this app to Codeigniter. Now when I paste this above code in CI it gives me errors. I have dixed that required part error with following statement.

require_once APPPATH."third_party/elasticsearch/vendor/autoload.php";

But i am not able to fix

use Elasticsearch\ClientBuilder;

It is constantly giving me syntax error. anyone knows how to fix it?

Please help. Thanks

Omicans
  • 531
  • 1
  • 8
  • 26
  • I also got an error in use statement when i included dompdf library. I solve the error by moving the require and use at the beginning of the code before class. – Geordy James Jan 06 '17 at 11:07
  • 2
    So in your case first after if ( ! defined('BASEPATH')) exit('No direct script access allowed'); require_once APPPATH."third_party/elasticsearch/vendor/autoload.php"; then use Elasticsearch\ClientBuilder; then class declarations... – Geordy James Jan 06 '17 at 11:08

1 Answers1

2

the simple way is using config/autoload.php file. put your code as a library, and make it autoload.

but if you are gonna have lots of classes you wanna import, it's not a practical approach. here is what i did: i made a folder specifically for my own files and libraries, namespaced it, and made it autoload.

now let's say you put your files in MyProject folder and namespaces are matched with paths. like MyProject/Bases/Class1.php has namespace MyProject/Bases.

then you add this code at the end of your config/config.php file.

spl_autoload_extensions('.php'); // Only Autoload PHP Files

spl_autoload_register(function($classname){
    
    if( strpos($classname,'\\') !== false ){
        // Namespaced Classes
        $classfile = /*strtolower(*/str_replace('\\','/',$classname)/*)*/;
        
        if($classname[0] !== '/'){
            $classfile = APPPATH.''.$classfile.'.php';
        }
        
        require($classfile);
        
    } else if( strpos($classname,'interface') !== false ){
        // Interfaces
        strtolower($classname);
        require('application/interfaces/'.$classname.'.php');
    }
    
});

this piece of code auto loads all the files namespaced in the application directory. now you can add any file you want, namespace it according to its directory path, and 'use' it in your classes.

thanks Thimothy Perez for his answer here

Community
  • 1
  • 1
Fatemeh Majd
  • 719
  • 8
  • 22