Creating a Library - Part 1

Posted by Tuts Admin on 2018-07-26



Want to be a contributing author and help grow the CodeIgniter community?

Register and account and use the contact form and drop us a note.



We appreciate any donation you're willing to send.

Visit the donations page

Donations collected are used to pay for hosting, domain names, further development of the website, and gives me a little more time to write tutorials.


Get an email when new content is added.

0 v4-dev Libraries Beginner

Creating a library - Part 1

Notice: CodeIgniter 4 is currently in development as of the writing of this article. This article is aimed at beginners.

We're all excited for the coming release of CodeIgniter4. For fun, we'll look at how to create a new, custom library in the new version of this popular framework.

When creating a custom library you'll need to understand Namespaces. Don't worry, I'm not going to get too in-depth, just what you need to know for this article.

Namespaces in the application folder is fairly easy to remember and understand.

application/Libraries lives in the App\Libraries namespace; application/Controllers lives in the App\Controllers namespace.

See the pattern here? There's only an exception or two but we won't go into that just now.

Now we'll create a file named MyLib.php and save it to application/Libraries. You can name it whatever you like, but the file name and class name must match, just like you're used to with CodeIgniter 3.

Now we'll edit the file with our favorite text editor. At the top of each file you'll need the obligatory <?php tag. Then you define the namespace thusly:

<?php namespace App\Libraries

So far so good? Excellent.

Next you define the class thusly:

class MyLib{}

You can name it whatever you like, of course.

It's good practice to use class properties when you need them, so you'll want to add those as well.

class MyLib {

        // define a blank property
            public $var1;

             // Assign a default value
            public $var2 = "HI"; 

Whenever you need them now, you can refer to them as $this->var1 and $this->var2 respectively within the class.

Now that we have our file created with a proper namespace, a class, and class properties we can add our class methods.

class MyLib {

            public $var1;

            public $var2 = "HI";  // Assign a default value

            public function returnVarOne()
                return $this->var1;


And that's it. That's all you need to know to get started with creating custom libraries in CodeIgniter4.

In the next article on creating libraries, we'll take a look at how to include CodeIgniter4's core functionality along with a few more advanced methods.

Stay Tuned!