Codeigniter – Seeder

Imamo bazu podataka a projekt nam je u razvoju. Baza je naravno prazna jer nemamo stvarnih korisnika. Seeder nam tu služi kao mehanizam s kojim možemo popuniti bazu podataka sa “lažnim” podacima. Na ovaj način simuliramo realno korištenje projekta.

Prije svega, kako pripremiti projekt? Vidi ovdje.

Faker

Faker je lib koji dolazi sa Codeigniter-om. Njegova svrha je da stvara lažne podatke (fake data).

Za testiranje, idemo na http://localhost:8080/ i koristimo “Home” kontroler u “app/Controllers/Home.php” sa ovim preinakama:

<?php

namespace App\Controllers;
use Faker\Factory;

class Home extends BaseController
{
    public function index()
    {		
		$faker = Factory::create();
		return $faker->name();
    }
}

Kao što vidimo, faker nam vraća neko “bezveze” ime svaki put kada osvježimo preglednik. Ako odemo na “./vendor/fakerphp/faker/src/Faker/Generator.php”, vidimo listu svih mogućih opcija:

@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()

Džungla dostupnih metoda je masivna.

Baza podataka

Ubacite SQL u bazu:

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;

Pa u terminalu unesite ovu naredbu:

php spark make:seeder User --suffix

S ovim generiramo datoteku “./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(),            
        ];
    }
}

Nakon što smo dodali “faker”, pokrećemo naredbu:

php spark db:seed UserSeeder

…i imamo podatke u bazi!

Odgovori

Vaša adresa e-pošte neće biti objavljena.

Previous post Codeigniter – migracija
Next post Typescript – bilješke

🗣 You can translate this site using Chrome built-in translator.