What name would be given to a dumb, data class? - php

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

Related

Extracting data from DDD Entity/Aggregate

Can someone please clarify the following topic? I haven't found enough complex answer to this, just some basic examples of how this should work, so I am asking here.
Let's say we have an entity Invoice. The Invoice has some private props like date issued, payment date, Items, etc.
By the principle of DDD the Domain should care only about itself and never about the world around. In case of Invoice it means, you can issue it, you can add item, you can probably change the payment date etc.
But is responsibility of the Invoice to care about extracting data from it? I mean, e.g. in Doctrine you would create getters for all of the properties and it would be definitely fine. But I believe this is not something you want to do in DDD - I think the Invoice should care only about it's state and modifying it and not about providing hundreds of getters for all of its properties.
So my question is - what is the best way, to extract data from Entity to e.g. DTO? Is it really getters? Or should you use maybe the reflection? Entity => Transformer (using Reflection) => DTO?
By the way, when you are converting Entity to DTO, should you use the third, transformer, class, or invoke some method on Entity to convert itself into the DTO (like $Invoice->toDetailDto())? I think that calling ->toDetailDto is violation of Single responsibility, but on the other side, it solves the problem with accessing private properties of Entity without using Reflection and without hundreds of getters.
Can someone please clarify the following topic?
This is not your fault -- the literature sucks.
By the principle of DDD the Domain should care only about itself and never about the world around
Yeah, about that... it's kind of a lie. Pouring information into an object is pointless unless there is some way of getting the information back out. (Analogy: /dev/null is an awesome database if you don't need to get information back out of it again.)
"How do I get information out of you?" is part of the contract of the object; that part of the contract might be questions that you ask the object to get information, or it might be that the object sends information "somewhere else", and you can look there.
For example, the cargo shipping demonstration, the Cargo "aggregate root" includes a number of methods for copying information out of the object.
For something like a DTO, part of the riddle is figuring out whether the domain model interface should include a dependency on the DTO definition. Most commonly, the answer is no: dependencies normally point toward the domain model, rather than away from it. But "no" isn't the only possible answer; if the DTO definition is stable (because, for example, it is defined by some industry standard), then you aren't any more likely to run into problems there than you are with using Strings or numbers.
Reflection... it can be the right choice. If nothing changes, or if everything always changes in lock step, then reflection is fine. When you need to change the implementation of the domain model and keep the definition of the DTO stable so that you don't break clients, it may get messier, depending on how many different places in the code apply reflection to the domain model, and whether or not you can find them all when the time comes.

Object and class structure for a larger project in PHP

Im about to start a large project in PHP. I want the code to be as clean as possible so I've started learning programming with classes & objects. Question is, is this the right way to structure it?
What I was thinking is three main classes. do, get and general
In general i will have a function for connecting to database.
In do i will store all functions that is inserting or updating the database for example:
class do
{
function createUser($name){
// Do stuff to create user
}
function like($id){
// Do stuff to like the id
}
}
$do = new do;
$do->like("52");
$do->createUser("Bob");
Question is, is this the right way to do this? Will this get sloppy when there are more than 20 functions in do or get?
Thanks in advance!
Remember that an object represents a thing, a noun (and a class is the type of thing); "do" is a verb, which is a pretty big clue that it's not a good choice for an object.
In fact, here, it's more like a namespace of "vaguely action-y functions", in contrast to the "get" namespace of "vaguely retrieval-y functions". Namespaces are cool too, but they should be static classes, or actual namespaces - you never need to refer to an "instance" of one, they just sit there.
As for "general", you should never, ever, plan a catch-all like that; it's like giving up on categorising your code before you started. You might end up with one later, for things you really can't put anywhere, but you should be really disappointed if you do.
The objects in the code you've mentioned here might be:
the database connection
a user
whatever thing it is that $id represents
Note that last one: an "ID" is not a thing either, it's an identifier for finding a particular thing.
In $do->like("52");, neither $do nor "52" have any real meaning. But if "52" is the ID of a page, and a user is doing the liking, a (very simple) OO implementation might look like this:
$page = Page::getByID("52");
$current_user->like( $page );
Or perhaps:
$page = Page::getByID("52");
$page->addLike( $current_user );
Immediately, the code is more readable, and relationships between your objects become clear. And that is why OOP is such a popular paradigm for organising code.
I've stuck to the basics here to get the main idea across; a modern OOP framework would go a lot further than this in turning things into objects; for instance:
"factories" and "repositories" allow creating and loading/saving objects without that static getByID call
a db connection object would be passed into objects that needed it, rather than them assuming they can create their own, which is known as "dependency injection"
I'd say, as a personal preference, that classes and objects are a great way to go. However, you're probably going to want to change "do" and "get" into "changes" and "retrievals" or something equally meaningful to you. Using keywords as class names is considered a really evil practice.

why interfaces in dynamic/loosely-typed languages?

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.)

Bad practice to use Variable functions?

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.

Why should I use classes rather than just a collection of functions? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What are the benefits of OO programming? Will it help me write better code?
OO PHP Explanation for a braindead n00b
Just started learning/playing with creating classes in PHP and I'm wondering what pain do they solve? It seems like I can get the same job done with just a collection of functions that I include into the file. So my question is: Why should I use classes?
The Three Pillars of Object Oriented Programming. Learn them well:
http://codeidol.com/csharp/learncsharp2/Object-Oriented-Programming/The-Three-Pillars-of-Object-Oriented-Programming/
Encapsulation
The first pillar of object-oriented programming is encapsulation. The idea behind encapsulation is that you want to keep each type or class discreet and self-contained, so that you can change the implementation of one class without affecting any other class.
Specialization
The second pillar of object-oriented programming , specialization , is implemented through inheritance ; specifically by declaring that a new class derives from an existing class. The specialized class inherits the characteristics of the more general class. The specialized class is called a derived class, while the more general class is known as a base class.
Rather than cutting and pasting code from one type to another, the derived type inherits the shared fields and methods. If you change how a shared ability is implemented in the base class, you do not have to update code in every derived type; they inherit the changes.
Polymorphism
Polymorphism allows values of different data types to be handled using a uniform interface. The primary usage of polymorphism is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run time
See also:
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
http://en.wikipedia.org/wiki/Type_polymorphism
It's a way to view your code in a more intuitive, real-world way. (You package the data and all possible operations on that data together.) It also encourages encapsulation, abstraction, data hiding... What you're really looking for is the advantages of OOP.
Basically, classes allow you to put your data with the code - i.e. organization.
Also, classes allow your "followers" to customize your classes without rewriting your code, but rather creating new inherited classes.
Every class-based code might be rewritten with functions, but it would be much harder to understand.
Generally, its so that you can customize the behavior of that set of functions. Typically you have a bunch of functions that work in concert.
People who use these functions may want to only modify one of them for some special case. Or maybe you provide a class that forces the functions to interact in a certain why, but you can't define what they'll actually do.
A trite example: imagine if you had some library to check that some things didn't overlap.
class Comparator:
def Greater(self, left, right): pass
def Less(self, left, right): pass
def EnforceNoOverlap(self, comparator, left, right)
assert comparator.Greater(left, right) != comparator.Lesser(left, right)
It a way to make your code more granular, with proper data hiding, separation of concerns and some other best practices.
IMO using only functions in your code sooner or later leads to spaghetti-code that is hard to maintain and extend. It's harder to fix bugs, its harder to implement new features, because often there are lots of code replication.
Also you can't use polymorphism in your code design, so you can't work with abstractions.
the classes/object is the way of implementation object-oriented application design. it covered detailed in numerous OOAD/OOP books.

Categories