Maybe I've just been entirely ignorant to the solution to my issue and, hell, maybe it's built-in... I just haven't been able to find su开发者_开发知识库ch a solution. I've been looking passively for the last two weeks and actively for the last day.
How can I gracefully handle a foreign key constraint in symfony?
I've considered catching the exception (Doctrine_Connection_Exception) and assuming it was a foreign key constraint, then forwarding the user to an error module with an action for foreign key constraints. However, the code redundancy is atrocious and, even if I do put it into my base action class, having to put a try-catch block around each call to the database would get ugly. Not to mention, the assumption the exception is for a foreign key constraint is a horrible idea since this exception is called when there's SQL syntax and actual connection errors, as well.
I've thought about using the getPortableCode() and getPortableMessage() methods--which are inherited from the exception class--to determine if it's a foreign key constraint (which they can do) but they give absolutely no information about the constraint itself. For instance, when a constraint exception is thrown, getPortableCode() returns '-5' and getPortableMessage() returns 'already exists'. Granted, I could probably figure out what failed and throw up an error for my user if there was a single constraint, but, of course, I've made things complicated with multiple constraints.
Anyway, enough of my rambling, I'm trying to figure out what other developers are doing in my situation... It seems like this should be something covered in the lackluster "gentle introduction."
The answer to this question depends on what's creating the database entries.
If the answer is a form submission, you should be using Symfony's validation system. Doctrine provides validators for checking whether a relation is valid or an object exists. Take a look at sfValidatorDoctrineChoice and sfValidatorDoctrineUnique.
If you're creating the database entries not based on user input, the solution here is to perform the check yourself, either via a validator or a manual DB call. I suppose you could try/catch as well.
精彩评论