开发者

PHP MySQL How to organize this code?

开发者 https://www.devze.com 2023-02-04 02:38 出处:网络
I have this code (removed param escaping just to cut down some code): private function _get_tag_id($value)

I have this code (removed param escaping just to cut down some code):

private function _get_tag_id($value)
{
    $sql = "INSERT INTO tags (tag, added) VALUES ('$value', ".time().") "
         . "ON DUPLICATE KEY UPDATE tag_id = tag_id";
    $id = execute($sql);

    if (empty($id))
    {
        $sql = "SELECT tag_id FROM tags WHERE tag = '$value'";
        $id = execute($sql);
    }

    return $id;
}

I'm really bad at organizing my code and I've been reading about the importance of keeping your code DRY. Does this include any queries you might have? For example, I need to perform these same queries for a few fields, and what I've done is change it to this:

private funct开发者_如何学Goion _get_field_id($field, $value)
{
    $sql = "INSERT INTO {$field}s ({$field}, added) VALUES ('$value', ".time().") "
         . "ON DUPLICATE KEY UPDATE {$field}_id = {$field}_id";
    $id = execute($sql);

    if (empty($id))
    {
        $sql = "SELECT {$field}_id FROM {$field}s WHERE {$field} = '$value'";
        $id = execute($sql);
    }

    return $id;
}

Although that reduces some similar functions, it also makes the query much harder to read at first. Another problem after doing this is what happens if sometimes the query may be slightly different for a field? Let's say if the field is tag, I don't need the added column any more and maybe the query would now change to:

$sql = "INSERT INTO {$field}s ({$field}".($field == 'tag' ? '' : ", added").") "
     . "VALUES ('$value', ".($field == 'tag' ? '' : time()).") "
     . "ON DUPLICATE KEY UPDATE {$field}_id = {$field}_id";

Now it's starting to get extra messy, but I have a feeling people don't actually do that.

Another thing I've read is that functions should only do one thing. So would I cut up this function like this?

private function _get_tag_id($value)
{
    $id = $this->_add_tag_id($value);

    if (empty($id))
    {
        $id = $this->_get_tag_id($value);
    }

    return $id;
}

Or would it be better to leave it the way it was before?

If you don't think either of the ways I've tried organizing the code is correct also feel free to suggest the way you'd do it, or in other words what would be the best way to organize these simple bits of code?


I would turn it upside down - select first, and insert if not found.

Two reasons:

1) You will select and find more often that select and miss, so select first is on average faster.

2) "on duplicate key" is a non-standard extension to INSERT that will cause problems in the future if you should ever move to a SQL database without it. (I think it is MySQL only).

As for which is better, I'd rather try to understand the first or third.

0

精彩评论

暂无评论...
验证码 换一张
取 消