Faker is one of the most popular PHP library for generating fake data. I quite often use this library at the start of my project. Laravel has built-in faker library but for codeigniter I have to add faker as a third party library.
So in this post I am going to show you how to integrate faker into codeigniter.
Integrate Faker into Codeigniter:
Following are the steps involves in integration process:
- Download codeigniter 3.x from https://codeigniter.com/download
- Download or clone faker library from https://github.com/fzaninotto/Faker
- Copy faker src folder fo the codeigniter->application->thirdparty and rename src folder as faker.
- Add include path in the controller in this example I will use Welcome.php controller.
- Use Faker\Factory::create() to create and initialize faker
Codeigniter Folder Structure:
After downloading default codeigniter structure is something like this.
Faker Folder Structure:
After downloading from github faker folder structure look like below.
Copy Faker Src folder to application/third_party:
Now copy faker src folder to codeigniter/application/third_party folder and rename src folder to faker.
Add Include path to the Controller (controllers/welcome.php):
Copy below Path to index function of welcome.php
1 2 3 |
include APPPATH.'/third_party/faker/autoload.php'; |
Now initialize and use faker by assigning it to the variable.
1 2 3 4 5 6 7 8 9 10 11 12 |
$faker = Faker\Factory::create(); $faker->seed(5); echo "<strong>Title: </strong>".$faker->title; echo "<br>"; echo "<strong>First Name: </strong>".$faker->firstName; echo "<br>"; echo "<strong>Last Name: </strong>".$faker->lastName; echo "<br>"; |
Your final index function will look something like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public function index() { include APPPATH.'/third_party/faker/autoload.php'; $faker = Faker\Factory::create(); $faker->seed(5); echo "<strong>Title: </strong>".$faker->title; echo "<br>"; echo "<strong>First Name: </strong>".$faker->firstName; echo "<br>"; echo "<strong>Last Name: </strong>".$faker->lastName; echo "<br>"; echo "<strong>Street Address: </strong>".$faker->streetAddress; echo "<br>"; echo "<strong>Postcode: </strong>".$faker->postcode; echo "<br>"; echo "<strong>City: </strong>".$faker->city; echo "<br>"; echo "<strong>Country: </strong>".$faker->country; echo "<br>"; //$this->load->view('welcome_message'); } |
Also read:
- How to use Faker – PHP library that generates fake data
- Insert dummy data into MYSQL using PHP
- How to install Codeigniter in Xampp
- How to install GIT on Windows 10
- Simple role based access control example using PHP and MYSQLi