good way to interact with MySQL?
So what I currently have is my tables in SQL, with table connecting different table, e.g.
Table1: id, identifier, other_attributes
Table2: id, identifier, other_attributes
Table3: id, table1_id, table2_id // this connects table 1 and 2.
So I have made an开发者_运维问答 object for table1 and table2, allowing things like $table = new table1($id);
and $table->getName();
or $table->setName();
However, I'm not quite sure if this is the best way? And if it is, would it be best to create another object for table3? or is there better way to do this?
Finally, what I've done is combine getters and setters, meaning $table->name('somename');
will set the name, and $table->name();
will get it. Is it wise to combine them? or better to separate them?
Hosh
I would use objects for each really used object (as the name states somehow…).
For example I have a single user-class, which uses data from three different DB-tables. The n:m relation-tables should be implemented as their names indicate. Having a table 'user_has_address', I would implement the SQL-queries on the user-class too (which the uses an Address-class). But data from a table like 'company_has_employees' would reside in a company-class.
And how to name your getters and setters in PHP is a matter of coding-convention (e.g. in your company or just your own). You don't need them at all in PHP when using magic-methods (like __call()), but as noted by @JJ, it would make testing easier.
If I were implementing this, I wouldn't use name('somename')
and name()
as setters and getters as you have done. It makes it easy to remember the functions however in my opinion it also makes it a lot easier to make and find coding mistakes. You might accidentally type .name() when you actually mean .name(''), etc and finding such errors in code could be difficult.
I would go with .getName()
and .setName('somename')
myself. Maybe I'm biased - I have a strong Java background.
I would also strongly recommend getName() and setName(). The reason is simple: A good IDE can avoid typing work.
For example you type:
$name = 'str';
$table->setN
and then code completion can kick in which could lead to $table->setName($name). If you've only got a name($name = null) method, the IDE can not be sure whether or not to suggest an argument. Additionally, it is veeeery common to use setX()/getX() which helps to understand your code.
精彩评论