2017-05-21 13 views
0

私はこのURLタイプを持っています。比較URLモデルと実際の1

例: /segment1/123-title-of-the-item
または/segment1/title-of-the-item-123
または/segment1/DLCK34Z-other-text

など..

はのは、最初の例を考えてみましょう:

モデルは/segment1/{id}-{slug}

するためでありますデータベースから項目を取得する、私はする必要がありますアイテムの「123タイトル」からIDを特定する。

は、私は配列のように取得する必要があります。つまり

['id'] => 123 
['slug'] => title-of-the-item 

、私は、URLのサブストリングpatner要素に対応するすべてのケースのために知っておく必要があります。

{}の間のフィールドはすべて、データベーステーブルのフィールドです。アイテムのテーブル名はすでにわかっています。

スクリプト、クラス、機能、または提案はありますか?

+0

最後の例では、DLCK34Zは{id}の代わりに{item_code}なので、その場合は[item_code '] => DLC34Zを取得する必要があります – user3275570

答えて

0

ナイーブな実装:

<?php 

$url = '/segment1/x-title-of-the-item-123'; 

// Get the last segment/part 
$urlParts = explode('/', $url); 
$lastPart = end($urlParts); 

// Get ID and slug 
$candidates = explode('-', $lastPart); 

if ($object = findObjectById(current($candidates))) { 
    echo 'ID is at the beginning'; 
} else if ($object = findObjectById(array_pop($candidates))) { 
    echo 'ID is at the end'; 
} else { 
    // No valid ID anywhere 
    throw new \Exception('Database record not found'); 
} 

// This is a dummy function, replace it with your own implementation 
// that tries to find the database recod by the id. 
// Attention: ID can be a string or a bool (false). 
function findObjectById($id) 
{ 
    // Return the database record if it exists or null/false if not 
    // Attention: Won't work with the code above if 0 is a valid result! 
    return ((int) $id > 0); 
} 

しかし、私は他の誰かが良いアイデアを思い付くますかなり確信しています。

更新:はい、DLCK34ZがIDでない場合、その場合、私の試行はうまくいかないでしょう。あなたは、findObjectByCodeメソッドでそれを拡張することができますが、物事は乱雑になります。

関連する問題