Question

I want to create a unique code for a Download object

Currently the model is extending Kohana's create function

public function create(Validation $validation = NULL)
{
    // fails as there is no $user_id passed through...
    $this->code = $this->generate_code($user_id);

    parent::create($validation);
}

which is calling:

protected function generate_code($user_id)
{
    $code = $user_id.str_pad($this->id, 6, '0', STR_PAD_LEFT);

    return $code;
}

I have two problems: first I want to use the user_id at the beginning of the code. I was thinking about calling a static function in the User Model to get it but think that is a bad idea because I have read it is better to make models independent of other models. What is a better way of doing this, perhaps via the value in the session data (or is that bad practice)?

Second problem is that I would like to add the Download id to the end of the code (which is an auto incremented value) however this value will only be set after it has been created, but it will fail have the generate_code after the creation because the code column in the database is set to unique. Is there an elegant workaround for this?

edit: I fixed the second issue by adding the id after it was created e.g.:

public function create(Validation $validation = NULL, $user_id)
{
    $this->code = $user_id.time();

    parent::create($validation);

    $this->code = $this->code.str_pad($this->id, 6, '0', STR_PAD_LEFT);
}
Was it helpful?

Solution

Your logic requires that there must be user id present in generate_code() method. So it's not "bad practice". Just pass User object to Dowload objects create() method (it's called dependency injection). And I didn't understood your second part of the question, can you be more specific?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top