Saturday, July 13, 2024
CodeIgniter - seeder
We have a database and the project is under development. The database is of course empty because we have no real users. Seeder serves us here as a mechanism with which we can fill the database with "fake" data. In this way, we simulate the real use of the project.
First of all, how to prepare the project? See here.
Faker
Faker is a lib that comes with Codeigniter. Its purpose is to create fake data.
To test, go to http://localhost:8080/ and use the “Home” controller in “app/Controllers/Home.php” with these modifications:
<?php
namespace App\Controllers;
use Faker\Factory;
class Home extends BaseController
{
public function index()
{
$faker = Factory::create();
return $faker->name();
}
}
As we can see, the faker returns us some "nonsense" name every time we refresh the browser. If we go to "./vendor/fakerphp/faker/src/Faker/Generator.php", we see a list of all possible options:
@property string $citySuffix
@method string citySuffix()
@property string $streetSuffix
@method string streetSuffix()
@property string $buildingNumber
@method string buildingNumber()
@property string $city
@method string city()
@property string $streetName
@method string streetName()
@property string $streetAddress
@method string streetAddress()
@property string $postcode
@method string postcode()
@property string $address
@method string address()
@property string $country
@method string country()
@property float $latitude
@method float latitude($min = -90, $max = 90)
@property float $longitude
@method float longitude($min = -180, $max = 180)
@property float[] $localCoordinates
@method float[] localCoordinates()
@property int $randomDigitNotNull
@method int randomDigitNotNull()
@property mixed $passthrough
@method mixed passthrough($value)
@property string $randomLetter
@method string randomLetter()
@property string $randomAscii
@method string randomAscii()
@property array $randomElements
@method array randomElements($array = ['a', 'b', 'c'], $count = 1, $allowDuplicates = false)
@property mixed $randomElement
@method mixed randomElement($array = ['a', 'b', 'c'])
@property int|string|null $randomKey
@method int|string|null randomKey($array = [])
@property array|string $shuffle
@method array|string shuffle($arg = '')
@property array $shuffleArray
@method array shuffleArray($array = [])
@property string $shuffleString
@method string shuffleString($string = '', $encoding = 'UTF-8')
@property string $numerify
@method string numerify($string = '###')
@property string $lexify
@method string lexify($string = '????')
@property string $bothify
@method string bothify($string = '## ??')
@property string $asciify
@method string asciify($string = '****')
@property string $regexify
@method string regexify($regex = '')
@property string $toLower
@method string toLower($string = '')
@property string $toUpper
@method string toUpper($string = '')
@property int $biasedNumberBetween
@method int biasedNumberBetween($min = 0, $max = 100, $function = 'sqrt')
@property string $hexColor
@method string hexColor()
@property string $safeHexColor
@method string safeHexColor()
@property array $rgbColorAsArray
@method array rgbColorAsArray()
@property string $rgbColor
@method string rgbColor()
@property string $rgbCssColor
@method string rgbCssColor()
@property string $rgbaCssColor
@method string rgbaCssColor()
@property string $safeColorName
@method string safeColorName()
@property string $colorName
@method string colorName()
@property string $hslColor
@method string hslColor()
@property array $hslColorAsArray
@method array hslColorAsArray()
@property string $company
@method string company()
@property string $companySuffix
@method string companySuffix()
@property string $jobTitle
@method string jobTitle()
@property int $unixTime
@method int unixTime($max = 'now')
@property \DateTime $dateTime
@method \DateTime dateTime($max = 'now', $timezone = null)
@property \DateTime $dateTimeAD
@method \DateTime dateTimeAD($max = 'now', $timezone = null)
@property string $iso8601
@method string iso8601($max = 'now')
@property string $date
@method string date($format = 'Y-m-d', $max = 'now')
@property string $time
@method string time($format = 'H:i:s', $max = 'now')
@property \DateTime $dateTimeBetween
@method \DateTime dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null)
@property \DateTime $dateTimeInInterval
@method \DateTime dateTimeInInterval($date = '-30 years', $interval = '+5 days', $timezone = null)
@property \DateTime $dateTimeThisCentury
@method \DateTime dateTimeThisCentury($max = 'now', $timezone = null)
@property \DateTime $dateTimeThisDecade
@method \DateTime dateTimeThisDecade($max = 'now', $timezone = null)
@property \DateTime $dateTimeThisYear
@method \DateTime dateTimeThisYear($max = 'now', $timezone = null)
@property \DateTime $dateTimeThisMonth
@method \DateTime dateTimeThisMonth($max = 'now', $timezone = null)
@property string $amPm
@method string amPm($max = 'now')
@property string $dayOfMonth
@method string dayOfMonth($max = 'now')
@property string $dayOfWeek
@method string dayOfWeek($max = 'now')
@property string $month
@method string month($max = 'now')
@property string $monthName
@method string monthName($max = 'now')
@property string $year
@method string year($max = 'now')
@property string $century
@method string century()
@property string $timezone
@method string timezone($countryCode = null)
@property void $setDefaultTimezone
@method void setDefaultTimezone($timezone = null)
@property string $getDefaultTimezone
@method string getDefaultTimezone()
@property string $file
@method string file($sourceDirectory = '/tmp', $targetDirectory = '/tmp', $fullPath = true)
@property string $randomHtml
@method string randomHtml($maxDepth = 4, $maxWidth = 4)
@property string $imageUrl
@method string imageUrl($width = 640, $height = 480, $category = null, $randomize = true, $word = null, $gray = false)
@property string $image
@method string image($dir = null, $width = 640, $height = 480, $category = null, $fullPath = true, $randomize = true, $word = null, $gray = false)
@property string $email
@method string email()
@property string $safeEmail
@method string safeEmail()
@property string $freeEmail
@method string freeEmail()
@property string $companyEmail
@method string companyEmail()
@property string $freeEmailDomain
@method string freeEmailDomain()
@property string $safeEmailDomain
@method string safeEmailDomain()
@property string $userName
@method string userName()
@property string $password
@method string password($minLength = 6, $maxLength = 20)
@property string $domainName
@method string domainName()
@property string $domainWord
@method string domainWord()
@property string $tld
@method string tld()
@property string $url
@method string url()
@property string $slug
@method string slug($nbWords = 6, $variableNbWords = true)
@property string $ipv4
@method string ipv4()
@property string $ipv6
@method string ipv6()
@property string $localIpv4
@method string localIpv4()
@property string $macAddress
@method string macAddress()
@property string $word
@method string word()
@property array|string $words
@method array|string words($nb = 3, $asText = false)
@property string $sentence
@method string sentence($nbWords = 6, $variableNbWords = true)
@property array|string $sentences
@method array|string sentences($nb = 3, $asText = false)
@property string $paragraph
@method string paragraph($nbSentences = 3, $variableNbSentences = true)
@property array|string $paragraphs
@method array|string paragraphs($nb = 3, $asText = false)
@property string $text
@method string text($maxNbChars = 200)
@property bool $boolean
@method bool boolean($chanceOfGettingTrue = 50)
@property string $md5
@method string md5()
@property string $sha1
@method string sha1()
@property string $sha256
@method string sha256()
@property string $locale
@method string locale()
@property string $countryCode
@method string countryCode()
@property string $countryISOAlpha3
@method string countryISOAlpha3()
@property string $languageCode
@method string languageCode()
@property string $currencyCode
@method string currencyCode()
@property string $emoji
@method string emoji()
@property string $creditCardType
@method string creditCardType()
@property string $creditCardNumber
@method string creditCardNumber($type = null, $formatted = false, $separator = '-')
@property \DateTime $creditCardExpirationDate
@method \DateTime creditCardExpirationDate($valid = true)
@property string $creditCardExpirationDateString
@method string creditCardExpirationDateString($valid = true, $expirationDateFormat = null)
@property array $creditCardDetails
@method array creditCardDetails($valid = true)
@property string $iban
@method string iban($countryCode = null, $prefix = '', $length = null)
@property string $swiftBicNumber
@method string swiftBicNumber()
@property string $name
@method string name($gender = null)
@property string $firstName
@method string firstName($gender = null)
@property string $firstNameMale
@method string firstNameMale()
@property string $firstNameFemale
@method string firstNameFemale()
@property string $lastName
@method string lastName()
@property string $title
@method string title($gender = null)
@property string $titleMale
@method string titleMale()
@property string $titleFemale
@method string titleFemale()
@property string $phoneNumber
@method string phoneNumber()
@property string $e164PhoneNumber
@method string e164PhoneNumber()
@property int $imei
@method int imei()
@property string $realText
@method string realText($maxNbChars = 200, $indexSize = 2)
@property string $realTextBetween
@method string realTextBetween($minNbChars = 160, $maxNbChars = 200, $indexSize = 2)
@property string $macProcessor
@method string macProcessor()
@property string $linuxProcessor
@method string linuxProcessor()
@property string $userAgent
@method string userAgent()
@property string $chrome
@method string chrome()
@property string $msedge
@method string msedge()
@property string $firefox
@method string firefox()
@property string $safari
@method string safari()
@property string $opera
@method string opera()
@property string $internetExplorer
@method string internetExplorer()
@property string $windowsPlatformToken
@method string windowsPlatformToken()
@property string $macPlatformToken
@method string macPlatformToken()
@property string $iosMobileToken
@method string iosMobileToken()
@property string $linuxPlatformToken
@method string linuxPlatformToken()
@property string $uuid
@method string uuid()
The jungle of available methods is massive...
Database
Insert SQL into the database:
CREATE TABLE users (
id int(5) unsigned NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
email varchar(100) NOT NULL,
address varchar(256) NOT NULL,
phone varchar(48) NOT NULL,
updated_at datetime DEFAULT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
After that, enter this command in the terminal:
php spark make:seeder User --suffix
With this we generate the file “./app/Database/Seeds/UserSeeder.php”:
<?php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
use Faker\Factory;
class UserSeeder extends Seeder
{
public function run()
{
for ($i = 0; $i < 10; $i++) // napravi 10 ulaza
{
$this->db->table('users')->insert($this->generate());
}
}
private function generate()
{
$faker = Factory::create();
return [
'name' => $faker->name(),
'email' => $faker->email(),
'address' => $faker->address(),
'phone' => $faker->phoneNumber(),
];
}
}
After adding "faker", we run the command:
php spark db:seed UserSeeder
...and we have data in the database!