Ok, really simple question - is it bad practice to use Variable functions in php?
I have a validator class that can use these and it makes sense to me but it does seem like it may be bad practice to do this?
EDIT: I can see that this there is going to be a lot of different opinions on this. Maybe if i explain how i intend to use them:
I have a base validator class with a method per field that i want to validate. I then have a classes that extend this base class and actually do the validating based on whatever logic i need. I have therfore called the methods in the base class after the fields they will validate. In the sub classes i can then simply loop through an array of required fields (whose keys match the field names also) and then simple call that function.
It seems really nice and clean but part of me keeps thinking its wrong.
EDIT: Where did those answers disapear to?
No, it's not bad practice. Variable functions exist for a reason. They are what other languages term callbacks, or function pointers; Used all the time for a variety of applications.
I can't judge your specific use case since you provide no code, but I don't think you can go very wrong here. At worst, you can degrade performance slightly with unnecessary function calls. At best, you're using them exactly as intended.
Related
I'm writing a pretty simple email mime parser for an application I'm developing, and was thinking it'd be a good idea to create a dumb data class to make as 'an email' but as an object.
This is all well and good, and this might be a terrible question for SO, but alas, I am asking anyway. What would you call said dumb data class?
As I'm writing the project in Symfony 2.2 I thought using the word 'Entity'; as broad a term as it is, wouldn't make as much sense and could cause confusion because of Entities being used in DocTrine. So, what's the term that's used for this kind of thing? Just to store data and potentially use methods on it, like an entity, to format or retrieve other bits of information.
If you use the class just to pass data around, that's a DTO (Data Transfer Object from Java) in my opinion.So EmailDto could work
If you add methods to it i'd just use Email as the name of the class, just to describe what is.
How about calling it (the Germans among us are free to ROFL ;-) ):
POPO - Plain Old PHP Object
Generic names for classes are things like Object, Entity, Thing, Data, Class, Handler, etc. Descriptive names are really good to avoid confusion, though. YMMV
I work in php, and the concept of interfaces seems to me a little useless here. From reading, I understand that interfaces are part of "design by contract", but without at least guaranteeing a return of a type of a particular kind, there really isn't any contract. It seems it's like a contract that reads, "We agree to do the following: '' " -- there are no terms of the agreement.
If I want a guarantee that an object has a method, it doesn't seem like interfaces are particularly useful. If I try to call a method that an object doesn't have, I get a Fatal Error, so I find out pretty quickly that that class doesn't have a method with that name. If I want to be smart and check beforehand whether a class has a method, then checking the interface, and seeing whether the object implements that interface doesn't seem to save me any more time than just checking that object directly ( which I would do anyways to see if the class had that method regardless of any interfaces it did or didn't implement).
In other words, just because I have a set of methods that have particular names, that doesn't guarantee me any particular behavior. If I'm guaranteed a return of a variable of a certain type, I at least have some inkling of what the output would be, and I can write code that uses an object with that interface, because I know what I'm getting out of it. If it returns a string, I can continue coding with at least the certainty that I'm dealing with a string output afterward. So I'm guaranteed at least some behavior when a return type is specified. Is guaranteeing behavior part of what interfaces are for, or no?
The only thing I can think of is that when I'm writing code, it serves as a post-it note to myself to be sure to create certain methods when writing that class later on. It seems more like scaffolding for when I'm writing the code; I don't see much benefit from when I'm actually using it. So it's more for me to keep the standard when I'm creating classes than when I'm writing them. This benefit doesn't really seem to be captured in the concept of design by contract.
What benefit(s) do you actually get from using an interface in dynamic/loose-typed languages like PHP? Are they great, or is it something that more robust OO languages implement, so PHP implements it also?
Interfaces are used when you actually expect an object to implement a method.
For example, if I'm building a DB wrapper and it supports behaviours, which you register yourself in a bootstrap, then before running your behaviours (for example, sluggable), I will check that they implement my "DB_Wrapper_Behaviour_Interface" by using:
if(!($behaviourObject instanceof DB_Wrapper_Behaviour_Interface)) {
throw new Exception("Your behaviour doesn't implement my interface");
}
Design by contract is made more difficult without return types, but don't forget to favour 'tell' over 'ask'.
I believe an interface to be something like a responsibility. You are coding and need a collaborator. You ask it to do something because the code you are working on can't do everything. So you're asking another object to do something. An interface guarantees that the collaborator will do the job, but hides the 'how' it's done part.
Now you could argue that there's no need for the formal contract here, since the system will throw an error anyway if the collaborator can't do what you're asking it to do. But I think that misses the point in using interfaces as a responsibility.
Getting a fatal error is not always "easy". Sometimes you have to go on a specific module/action to see that something is actually missing in your class.
The interface enables you to make sure every method is implemented and to document these method (what the parameters are exactly going to be, what the return values should look like). This is useful if the parameters/values are arrays with a particular structure and you don't want to use classes instead (for the sake of simplicty).
I want to note, that PHP 5.4 will support type hinting. Right now I think there is only type hinting for function arguments, but I suppose there will be for return values, too. (At least there already is an RFC, though a very old and outdated one.)
I'm reading programming best practices and it is said that when creating a function we should make it do a only single specific task.
I got model functions that retrieves data and it's related data. Example:
$this->Student->StudentAssignments();
Currently this function retrieves the student's assignments plus the question for each assignment and data about the student. I use them all. My dilemma is if I try to make separate functions that retrieves the related data (student and question datas) it's taxing since I'm producing more calls to the DB.
What would you guys suggest?
Something to keep in mind when doing this sort of refactoring...
I typically will have a Model->getSomethingAndSomethingElse functions in my models.
These functions are public and meant to be called as a substitute for doing complicated (or any) find calls from the Controller.
What I will usually do is then build up a small collection of private functions in the model.
In your case I might have something along the lines of...
Student->getStudentAssigmentsWithQuestions
that then calls some private functions i.e.
Student->getStudent which might call Student->joinStudentAssignment which in turn might call Assignment->joinAssignmentQuestion etc.
The double underscore prefixes have been removed since markdown wants to bold things because of them. If you are using php5 the underscores aren't really important anyways as long as you use the "private" or "proteced" keywords.
Basically I use the public method as a container for a group of very specific query building or association building private functions within the models. This allows me to have an api that has complex data returned, but I build the query or the result set (depending on the type of data, relationships involved or query complexity) from small pieces - that can ideally be purposed and used in more than one public function call.
I think you're doing fine. But you should reconsider renaming your function to
$this->Student->getStudentAssignmentsWithQuestions
Or whatever you think fit. I think one should try to do as few calls to the database as possible (I assume you're performing a join somewhere in there), instead of fetching each set of elements by specific methods. This can lead to the fact that you'll get more methods (and therefore have to write some more tests), but I think this is the right way to do it.
To defend the design argument:
Your method does just one single task; it fetches student's assignments with each assignment's questions.
No, if you're strictly concerned about code refactoring you should break down that blob into simpler functions that perform a single task as you said. Yes, you will hit more your database but considering how easy is to work with caching in cakephp, performance should not be an issue. And if it is, then you shouldn't worry about code refactoring at this point.
Today at work someone tried to convince me that:
{$obj->getTableInfo()}
is fine for smarty/mvc/templating because it is using an objects method. I argued that because it makes a call to the database it has no place being there and it should be in the controller (we don't actually use MVC). Am I right in my understanding of the logical separations that are used in MVC and generally in templating? Or is there something that I am missing?
You're right. He's wrong.
Database calls, no matter in what form, should live in the controller if you want to do MVC right.
Obviously people piss all over what it should be and do stuff like that, but it's not the correct way.
Well, there are no "official" rules or anything, but I think something like that belongs in the controller. I don't do anything in my view code except display variables, nothing more complex than an if or a foreach-type loop is allowed. Certainly not calling functions that access the database. That should all be loaded by the controller, the view should only decide whether it needs to display it or not.
Depends on its context and scope really.
Is $obj the controller or the model layer? That should answer whether or not it is valid in my opinion.
In response to reading the other answers.
The functions name in itself pertains it to being a simple getter method. It may make a call to the db through a controller layer. Which I would say is ok. Especially if it used some form of caching in memory. (ie the getter is the setter as you only want to cache it when it is used once.)
I am wondering whats the best practices regarding functions and objects. For example I want to perform an action called tidy. It will take my data as input and tidy it and return it.
Now I can do this in two ways. One using a simple function and the other using a class.
Function: $data = tidy($data);
Class:
$tidy = new Tidy();
$data = $tidy->clean($tidy);
Now the advantage in making it a class is that I do not have to load the class before. I can simply use the autoload feature of php to do so.
Another example is the database class. Now everyone seems to be using a separate class for db connectivity. But we usually have a single object of that class only. Isn't this kind of contrary to the definition of class and objects in a sense that we are using the class only to intantiate a single object?
I kind of dont understand when to use a function and when to use a class. What is the best practice regarding the same? Any guidelines?
Thank you,
Alec
For something that does one thing, and only one thing, I'd just use a function. Anything more complex, and I'd consider using an object.
I took the time to poke through some piles of (arguably ugly and horrible) PHP code and, really, some things could have been done as objects, but were left as functions. Time conversions and string replacements.
Functions typically do one specific task.
Objects represent something that have tasks associated with it. (methods)
Use a function for tidy. Plain and simple. ;-)
I'd personally make a 'data' object that handles data then have a tidy method under it.
This pattern will allow the number of tasks you do on data to expand while containing it all in a nice little self-contained chunk.
For your case, I'd make it a function, possibly a static function in something like a "util" class (for which the only purpose of the class is to act like a namespace - it'll group all your random useful methods together). As a rule of thumb, only use an object if it needs to store some data that needs to live between multiple function calls. That's why the database methods are made to be part of an object, because they store a database handle which is used between multiple function calls. Yes, there only ever is one database object, but having it as an object groups all the database-related stuff into one place, making it easier to maintain and keep bug-free.