GithubHelp home page GithubHelp logo

michalsn / codeigniter4-uuid Goto Github PK

View Code? Open in Web Editor NEW
40.0 6.0 8.0 122 KB

UUID package for CodeIgniter 4 with support for Model and Entity.

License: MIT License

PHP 100.00%
codeigniter4 uuid model entity

codeigniter4-uuid's Introduction

CodeIgniter 4 UUID PHP Tests

This package make it easy to work with UUIDs in Codeigniter 4. It provide four classes to make that possible: Uuid, UuidModel, UuidEntity and UuidCast. This implementation is tighly coupled with Ramsey\Uuid.

Installation via composer

composer require michalsn/codeigniter4-uuid

Manual installation

Download this repo and then enable it by editing app/Config/Autoload.php and adding the Michalsn\UuidModel namespace to the $psr4 array. For example, if you copied it into app/ThirdParty:

<?php

$psr4 = [
    'Config'      => APPPATH . 'Config',
    APP_NAMESPACE => APPPATH,
    'App'         => APPPATH,
    'Michalsn\Uuid' => APPPATH . 'ThirdParty/codeigniter4-uuid/src',
];

Versions

CodeIgniter version This package version
>= 4.5 >= 1.1
< 4.5 < 1.1

How to use it

In general, using UuidModel and UuidEntity is no much different than using the original classes provided with CodeIgniter 4 framework. We just have some additional config options. There is a good chance that you will not need to use Uuid class at all, because most of the things that happens are already automated.

Uuid

Working with Uuid class is really simple:

<?php

$uuid = service('uuid');
// will prepare UUID4 object
$uuid4 = $uuid->uuid4();
// will assign UUID4 as string
$string = $uuid4->toString();
// will assign UUID4 as byte string
$byte_string = $uuid4->getBytes();

If you have any additional configuration options to set to a specific UUID version then you can do it via config file.

UuidModel

UUID fields are always returned as a string even if we store them in byte format in the database. This decision was made because of the convenience of use. We don't have to worry about field type or conversion of the data.

Parameter Default value Description
$uuidVersion uuid4 Defines the UUID version to use.
$uuidUseBytes true Defines if the UUID should be stored in byte format in the database. This is recommended since will allow us to save over half the space. Also, it's quite easy to use, because we always translate UUID to a string form when retrieving the data or to a byte form when we are saving it.
$uuidFields ['id'] Defines the fields that will be treated as UUID. By default we assume it will be a primary key, but it can be any field or fields you want.

Now, let's see a simple example, how to use UuidModel in your code. In example below, there are no additional changes except that our model extends UuidModel. The primary key will be stored as UUID4 in the byte format in the database.

<?php

namespace App\Models;

use Michalsn\Uuid\UuidModel;

class Project1Model extends UuidModel
{
    protected $table      = 'projects_1';
    protected $primaryKey = 'id';

    protected $returnType = 'array';
    protected $useSoftDeletes = true;

    protected $allowedFields = ['name', 'description', 'created_at', 'updated_at', 'deleted_at'];

    protected $useTimestamps = true;

    protected $validationRules = [
        'name' => 'required|min_length[3]',
        'description' => 'required',
    ];
}

Now, here is an example where we will use the UUID but not as a primary key.

<?php

namespace App\Models;

use Michalsn\Uuid\UuidModel;

class Project2Model extends UuidModel
{
    protected $uuidFields = ['category_id'];

    protected $table      = 'projects_2';
    protected $primaryKey = 'id';

    protected $returnType = 'array';
    protected $useSoftDeletes = true;

    protected $allowedFields = ['category_id', 'name', 'description', 'created_at', 'updated_at', 'deleted_at'];

    protected $useTimestamps = true;

    protected $validationRules = [
        'category_id' => 'required',
        'name' => 'required|min_length[3]',
        'description' => 'required',
    ];
}

UuidEntity

Using the UuidEntity is only required if we store UUID fields in the byte format. In other case there are no benefits over original Entity class. The same as in the UuidModel, by default we assume that only primary key will have the UUID type.

Parameter Default value Description
$uuids ['id'] Defines the fields that will be treated as UUID. By default we assume it will be a primary key, but it can be any field or fields you want.

Now let's see a two examples which will match those for models that were previously shown.

<?php

namespace App\Entities;

use Michalsn\Uuid\UuidEntity;

class Project1Entity extends UuidEntity
{
    protected $attributes = [
        'id' => null,
        'name' => null,
        'description' => null,
        'created_at' => null,
        'updated_at' => null,
        'deleted_at' => null,
    ];
}
<?php

namespace App\Entities;

use Michalsn\Uuid\UuidEntity;

class Project2Entity extends UuidEntity
{
    protected $uuids = ['category_id'];

    protected $attributes = [
        'id' => null,
        'category_id' => null,
        'name' => null,
        'description' => null,
        'created_at' => null,
        'updated_at' => null,
        'deleted_at' => null,
    ];
}

And that pretty much it. No more changes are needed.

UuidCast

NOTE: Don't use this casting class if you intend to use the UuidModel class.

Since CodeIgniter now allows the use of custom cast classes in Entities, we've also added our own casting class. This casting class enables the UUID to be converted from byte to string during data retrieval and reverse on data setting. Normally you will not use the cast function as the transition from strings to bytes is done in the UuidModel class. With that in mind, you should only use this cast feature when you want to work with the Entity without using UuidModel class later.

This is a simple example of how we would use our casting class with Entity.

<?php

namespace App\Entities;

class MyEntity extends Entity
{
    protected $casts = [
        'id' => 'uuid',
    ];

    protected $castHandlers = [
        'uuid' => 'Michalsn\Uuid\UuidCast',
    ];
}

Limitations

For now this class doesn't support SQLite3 database when you want to strore UUIDs in a byte format.

Supported UUID versions

  • Version 1: Time-based - uuid1
  • Version 2: DCE Security - uuid2
  • Version 3: Name-based (MD5) - uuid3
  • Version 4: Random - uuid4
  • Version 5: Name-based (SHA-1) - uuid5
  • Version 6: Ordered-Time (nonstandard yet) - uuid6

License

The MIT License (MIT). Please see License File for more information.

codeigniter4-uuid's People

Contributors

asnanmtakim avatar michalsn avatar yassinedoghri avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

codeigniter4-uuid's Issues

find is not working after insert

once I insert data and then tries to find that record with find method by providing primary key returned by insert call, It returns all the records
$model = new CommoditiesModel(); $commodity = $model->insert($input); $commodity_data = $model->find($commodity);

find call is returning all the records without any WHERE clause.

UUID Helper

Is there any function in order to check if an string|binary variable is an uuid?

Bug: Argument passed to Michalsn\Uuid\Uuid::fromString() must be of the type string, null given.

Hey @michalsn!

I'm getting this error:

Argument 1 passed to Michalsn\Uuid\Uuid::fromString() must be of the type string, null given, called in /castopod-host/vendor/michalsn/codeigniter4-uuid/src/UuidModel.php on line 381

This happens when trying to insert a record with a null value in a Uuid field that should be converted in bytes. Here is the line in question, in the doInsert method:

if (in_array($key, $this->uuidFields) && $this->uuidUseBytes === true)
{
    $val = ($this->uuid->fromString($val))->getBytes(); // line 381, $val is null
}

Given that you may have a Uuid field with possible null values, there should be a check to prevent this from happening.

Possible solution

Add a condition to check that the field value is not null for insert and update:

if ($val && in_array($key, $this->uuidFields) && $this->uuidUseBytes === true)
{
    $val = $this->uuid->fromString($val)->getBytes();
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.