Elif Sahin
Elif Sahin

Reputation: 59

Adding composer to existing codeigniter project

I want to add Composer to my CodeIgniter project and autoload dependencies. I followed a few steps but I'm probably missing something. Here are the steps I followed.

In the config.php file I changed $config['composer_autoload'] to TRUE and I also tried changing it to FCPATH.'vendor\autoload.php' which didn't work.

Inside project root folder I used this command: composer require mpdf/mpdf and it created a vendor folder with mpdf in it.

After reading a bit, I made this change at the end of index.php:

/*
 * --------------------------------------------------------------------
 * LOAD THE BOOTSTRAP FILE
 * --------------------------------------------------------------------
 *
 * And away we go...
 */
include_once './vendor/autoload.php';
require_once BASEPATH.'core/CodeIgniter.php';

This is how the project structure is after the changes made:

project structure image

Here's the composer.json:

{
        "description": "The CodeIgniter framework",
        "name": "codeigniter/framework",
        "type": "project",
        "homepage": "https://codeigniter.com",
        "license": "MIT",
        "support": {
            "forum": "http://forum.codeigniter.com/",
            "wiki": "https://github.com/bcit-ci/CodeIgniter/wiki",
            "slack": "https://codeigniterchat.slack.com",
            "source": "https://github.com/bcit-ci/CodeIgniter"
        },
        "require": {
            "php": ">=5.3.7",
            "mpdf/mpdf": "^8.0"
        },
        "suggest": {
            "paragonie/random_compat": "Provides better randomness in PHP 5.x"
        },
        "require-dev": {
            "mikey179/vfsStream": "1.1.*",
            "phpunit/phpunit": "4.* || 5.*"
        }
    }

This is the controller I used to test mpdf:

    <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class TestingGround extends CI_Controller{
    public function index() {
        $this->load->view("testing_ground");
    }
    public function pdf(){

      $mpdf = new mPDF();

      // Write some HTML code:

      $mpdf->WriteHTML('Hello World');

      // Output a PDF file directly to the browser
      $mpdf->Output();

      }
}

This is the error I get: Class 'mPDF' not found C:\wamp64\www\kariyer_1.6\application\controllers\TestingGround.php 12

Upvotes: 1

Views: 1862

Answers (1)

Nico Haase
Nico Haase

Reputation: 12128

You have to use the proper class - mPDF uses namespaces, and as documented at https://mpdf.github.io/installation-setup/installation-v7-x.html, you have to instantiate it as following:

$mpdf = new \Mpdf\Mpdf();

Upvotes: 1

Related Questions