Simple UUID's

This is just a system I finished making up for a dev project of mine. I'm not sure how fool-proof is really it but so far it's been working perfectly for me. This is from the model.



	public function rules()


	{


		return array(


			array('id','default',


				'value'=>$this->uuid(),


				'setOnEmpty'=>false,'on'=>'insert'),


			array('id', 'unique', 'on'=>'insert')


		);


	}




	/**


	 * Creates a UUID


	 * @return UUID "a466eeb6-6139-cbad-abaf-8c3d8e0fb6f2"


	 */


	


	private function uuid($prefix = '')


	{


		$chars = md5(uniqid(mt_rand(), true));


		$uuid  = substr($chars,0,8) . '-';


		$uuid .= substr($chars,8,4) . '-';


		$uuid .= substr($chars,12,4) . '-';


		$uuid .= substr($chars,16,4) . '-';


		$uuid .= substr($chars,20,12);


		return $prefix . $uuid;


	}


dont know, if this generates a real uuid

mysql provides a function uuid() as well as cakePHP with String::uuid()

Quote

dont know, if this generates a real uuid

mysql provides a function uuid() as well as cakePHP with String::uuid()

I've used PHP's UUID system but it's said to be pretty horrid. Never heard that MySQL had UUID's and I toyed with CakePHP's.

Quite honestly it may not generate a 'real' UUID so if anyone would like to improve it by all means do so. But so far It's been working as intended. Granted "working" does not mean it's working correctly. I'll see if I can hack down CakePHP's to be better suited.

I'm using the exact same code that you are.

It works well enough.

http://en.wikipedia…_.28MD5_hash.29

Is what we are using ;)

Thanks a lot Bios Element !! :)

You should have got the format of uuid i.e 8x-4x-4x-4x-12x. Second you have to be sure that id is unique. I think that mysql generate the number order of the record automatically with every new record. Hashing this number using salted md5 will ensure that uuid is going to be atomic.

However, I’d like to know: could Yii able to deal with table that its primary key a uuid? In other words, Gii could understand it and generating the app skelton as usual?

  1. A UUID should look like this: xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx where N contains the variant and M contains the version of the variant. So not all bits of a good UUID number are free to choose.

  2. IMHO Yii can work with UUIDs as keys - it relies on the database to create the primary key and if you want to you can set it your self by appropriately using the beforeSave method for instance.