I have PHP application that is completely procedural (No PHP Classes). In my case, is there any formal diagrams I can draw to show how my web application that is equivalent to a UML class diagram for OOP based applications.
Thanks all
doxygen can generate call- and caller graphs automatically - if that suits your needs.
You could make some Hatley-Pirbhai models:
http://en.wikipedia.org/wiki/Hatley-Pirbhai_modeling
It's not because the implementation (or even the design) is procedural, that the business model is.
Though you may not find explicit reference to classes in your code, they may still be there, hidden, scattered through global variables etc, functions manipulating some globals, ...
So in order to describe your app, you may still be able to use a (conceptual) class diagram.
Related
For the life of me, I can't seem to wrap my head around "classes" in PHP.
I have managed to write large, scalable, and popular websites without them.
What am I missing? (And how do I learn?)
Classes will help with code re-use and potentially a very structured application.
Procedural programming can be a lot faster in both development time and execution speed.
OO programming is the more mainstream way but not always the best way. Theres a book called PHP Objects, Patterns and Practice which is a very good read, it covers the basics of classes, why and how to use, abstraction and common design patterns such as MVC. It also covers unit testing and other very good practices for php developers
The point of classes (object oriented programming) is that it bundles data together with the code that operates on it. If done well, this leads to less tightly coupled and thus more maintainable code.
In practice it means fewer global variables (whether used directly or accessed through static factory methods) and lesss passing around of data (i.e. smaller method signatures).
For a concrete example, look at the Mysqli extension: each function has a procedural and an OOP version, and the procedural version nearly always needs to have an extra "link" parameter to give it context, wheras the OOP version gets that context from the current object.
Everybody answered was right you are missing a lot because let's say you have a photo gallery website
instead of writing functions and in the end you end with a lot of them
OOP would be useful in:
Code organization and maintainability
Adds clarity, and reduce complexity
Emphasizes data over procedures
Code modularity
Code re-usability (Believe me you will need that a lot)
Well-suited for databases
I wasn't using OOP before but i started and to be honest not very long time ago, and found it very useful in those points specially in the re-usability of the code
Let's say i have a photo gallery website
i will create a class for users and this class will do CRUD on all of the users table
and a class for the photos to do the CRUD on all of the photographs table
I could also make a class to do all the CRUD for me without specifying on what table
and then use the inheritance to extend all the CRUD in my users class and my photograph class
the point in that is i could only write the CRUD methods once
and then re-use it in all of my other classes
I hope i would have answered your question
IMO, If you do not wish to seperate your htmls & php code; you better not use classes.
You'll need them in a framework environment (not necessarily), and you'll need them if you want to objectify your datas, handle them like that.
but if you're fine without it, then you're just fine :)
When it comes to handle a very complex system, with a lot of different data structures, more than one team members, etc. You and your code need to be organized very well, and you'll need classes.
Good question! You got my upvote!
Straight to the point:
You're missing a whole world!
There are many metaphors to describe it but there's nothing better than practice - you obviously know it after "years" of programming!
Decide on a small project and write it OOP style. Then you'll get the idea.
Take this tip as well: Name your classes as their file names (ex. "MyClass" -> "MyClass.php"). Easy to maintain.
You are probably missing testability: I guess your functions call other functions, which in turn might call another function, right? So you will have trouble testing an isolated function. With OOP you assemble "heaps" of objects and can interchange each object with a "fake" one (called mock or stub) for a test. This way, you can test each functionality in isolation. Think of being able to test you output code without needing a database. Think of testing your controller code (the code which processes the request parameters and decides what action to take) without needing a web server.
I am documenting a PHP4 system I'm building for a client. The system will be written following an object-oriented logic, using the MVC pattern. I have already sketched up a class diagram; however, I am now wondering if it makes sense to create object diagrams for such a system, since it follows the OOP model rather loosely.
The closest thing to object-oriented behavior in this system will probably be a handful of methods changing their behavior based on how they're being called, although this can't exactly be called instancing straight-up classes; would an object diagram capture anything useful from this scenario, or am I better off just skipping them altogether? Thanks in advance.
In my experience, UML Class diagrams are best used in an isolated context -- to describe a section of the system.
So my answer is that if you are describing a piece of your system in a document, and a UML class diagram would help a reader understand the relevant section of the system then you should do a diagram for that section and include it.
Doing one class diagram for the entire system is rarely, if ever, useful. And including various class diagrams without context is also rarely useful.
Be strategic in your use of UML; it's a communication tool, not a documentation tool. (Sort of like writing. Words on paper means nothing unless used and organized thoughtfully)
I think the flexibility of your situation conflicts with expectations of UML.
I would suggest abstracting the implementation level from your diagram (and lie) and represent the functionality of those methods as independent methods performing their own work.
I've been playing mostly with PHP and Python.
I've been reading about Interfaces in OO programming and can't see an advantage in using it.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
Do Interfaces were created in another languages because they don't provide multiple inheritance? Or am I missing something more important here?
First, and foremost, try not to compare and contrast between Python and Java. They are different languages, with different semantics. Compare and contrast will only lead to confusing questions like this where you're trying to compare something Python doesn't use with something Java requires.
It's a lot like comparing the number 7 and the color green. They're both nouns. Beyond that, you're going to have trouble comparing the two.
Here's the bottom line.
Python does not need interfaces.
Java requires them.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
The two concepts have almost nothing to do with each other.
I can define a large number of classes which share a common interface. In Python, because of "duck typing", I don't have to carefully be sure they all have a common superclass.
An interface is a declaration of "intent" for disjoint class hierarchies. It provides a common specification (that can be checked by the compiler) that is not part of the simple class hierarchy. It allows multiple class hierarchies to implement some common features and be polymorphic with respect to those features.
In Python you can use multiple inheritance with our without interfaces. Multiple inheritance can include interface classes or not include interface classes.
Java doesn't even have multiple inheritance. Instead it uses a completely different technique called "mixins".
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
If you create an interface in Python, it can be a kind of formal contract. A claim that all subclasses will absolutely do what the interface claims.
Of course, a numbskull is perfectly free to lie. They can inherit from an interface and mis-implement everything. Nothing prevents bad behavior from sociopaths.
You create an interface in Java to allow multiple classes of objects to have a common behavior. Since you don't tell the compiler much in Python, the concept doesn't even apply.
Do Interfaces were created in another languages because they don't provide multiple inheritance?
Since the concepts aren't related, it's hard to answer this.
In Java, they do use "mixin" instead of multiple inheritance. The "interface" allows some mixing-in of additional functionality. That's one use for an interface.
Another use of an Interface to separate "is" from "does". The class hierarchy defines what an objects IS. The interface hierarchy defines what a class DOES.
In most cases, IS and DOES are isomorphic, so there's no distinction.
In some cases, what an object IS and what an object DOES are different.
The usefulness of an interface is directly connected to the usefulness of static typing. If you're working in a dynamically-typed language like PHP or Python, interfaces truly don't add significantly to the expressiveness of the language. That is, any program that can be described as using interfaces can be expressed without significant difference without using interfaces.
As a result, Python has a fairly nebulous concept of a "protocol" (an implementation conforming to a certain pattern, like the iteration protocol) which amounts to essentially the same thing, but without the other benefits of compile-time checking its value is limited.
In a statically-typed language, on the other hand, an interface is essential to allow implementation to be decoupled from implementation. In a static language, the types of all expressions must be resolved at compile time, so normally bindings to implementation must be made at that time, limiting run-time flexibility. An interface defines how to access functionality without defining a specific implementation, which allows a static language to prove that expressions are correct without having access to the implementation.
Without interfaces (or an equivalent formulation like C++'s pure virtual functions), the expressiveness of a statically-typed language would be severely hampered. In fact, many implementations exist (Win32 and COM come immediately to mind) to essentially reproduce much of the functionality of interfaces and virtual dispatch in C by storing function pointers in structures (and thus re-implementing C++'s virtual functions and vtable invocation by hand). In this case there is a big difference in expressiveness, since many changes are required in the program to express the same concepts.
Interfaces are just one example of type polymorphism, and a fairly limited one at that. In languages that support parametric polymorphism (aka generics) you can accomplish much more. (For example, C#'s LINQ would not be possible without generic interfaces.) For a much more powerful form of the same kind of thing, look into Haskell's typeclasses.
Even in duck-typed languages like Python, an interface can be a clearer statement of your intent. If you have a number of implementations, and they share a set of methods, an interface can be a good way to document the external behavior of those methods, give the concept a name, and make the concept concrete.
Without the explicit interface, there's an important concept in your system that has no physical representation. This doesn't mean you have to use interfaces, but interfaces provide that concreteness.
In dynamically typed languages, like PHP and Python, interfaces are only of limited use. You can already attempt to call methods on any object whenever, and you get a run-time error if it doesn't exist.
It's in statically typed languages, like Java and .NET, that interfaces become important, because methods and their arguments are checked at compile-time.
Now, for interfaces:
Java has Lists in addition to arrays. As a general rule, arrays are for primitives (the number types mainly), while Lists are for objects.
I can have a List<String>, which is a list of strings. I know I can add strings to it, and get strings back from it.
I don't know which implementation it is. It could be an ArrayList (list backed by an array), a LinkedList (list backed by a doubly linked list), a CopyOnWriteArrayList (thread-safe version of ArrayList), etc...
Thanks to polymorphism and interfaces, I don't need to know which type of List it is to do List operations on it.
Because you want to program against an interface and not a concrete implementation (GoF 1995:18)
Because sometimes you don't want to provide an implementation.
Java Interface
Java class
Yes. As for PHP, interfaces are just a means to overcome the lack of multiple inheritance. There are minor semantic differences useful for IDEs, and fewer conflicts caused by interfaces clearly aid newbie programmers. But as said before, it's not strictly necessary in dynamic languages.
http://c2.com/cgi/wiki?MultipleInheritance
Please read Twisted Framework article about power of Zope Interfaces in python.
It's generally implemented to replace multiple inheritance (C#).
I think some languages/programmers use them as a way of enforcing requirements for object structure as well.
I've never been able to figure this out. If your language doesn't type-check, what benefits do interfaces provide you?
Interfaces cause your program to fail earlier and more predictably when a subclass "forgets" to implement some abstract method in its parent class.
In PHP's traditional OOP, you had to rely on something like the following to issue a run-time error:
class Base_interface {
function implement_me() { assert(false); }
}
class Child extends Base_interface {
}
With an interface, you get immediate feedback when one of your interface's subclasses doesn't implement such a method, at the time the subclass is declared rather than later during its use.
Taken from this link (sums it up nicely):
Interfaces allow you to define/create
a common structure for your classes –
to set a standard for objects.
Interfaces solves the problem of
single inheritance – they allow you
to inject ‘qualities’ from multiple
sources.
Interfaces provide a flexible
base/root structure that you don’t
get with classes.
Interfaces are great when you have
multiple coders working on a project
; you can set up a loose structure
for programmers to follow and let
them worry about the details.
I personally find interfacing a neat solution when building a DataAccess layer which has to support multiple DBMS's. Each DBMS implementation must implement the global DataAccess-interface with functions like Query, FetchAssoc, FetchRow, NumRows, TransactionStart, TransactionCommit, TransactionRollback etc. So when you're expanding your data-acccess posibilities you are forced to use a generic defined functionschema so you're application won't break at some point because you figured the function Query should now be named execQuery.
Interfacing helps you develop in the bigger picture :)
Types serve three distinct functions:
design
documentation
actual type checking
The first two don't require any form of type checking at all. So, even if PHP did no checking of interfaces, they would still be useful just for those two reasons.
I, for example, always think about my interfaces when I'm doing Ruby, despite the fact that Ruby doesn't have interfaces. And I often wish I could have some way of recording those design decisions in the source code.
On the other hand, I have seen plenty of Java code that used interfaces, but clearly the author never thought about them. In fact, in one case, one could see from the indentation, whitespace and some leftover comments in the interface that the author had actually just copied and pasted the class definition and deleted all method bodies.
Now to the third point: PHP actually does type check interfaces. Just because it type checks them at runtime doesn't mean it doesn't type check them at all.
And, in fact, it doesn't even check them at runtime, it checks them at load time, which happens before runtime. And isn't "type checking doesn't happen at runtime but before that" pretty much the very definition of static type checking?
You get errors if you haven't added the required methods with the exact same signature.
Interfaces often used with unit-testing (test-driven design).
it also offers you more stable code.
the interfaces are also used to support iterators (eg. support for foreach on objects) and comparators.
It may be weakly typed, but there is type hinting for methods: function myFunc(MyInterface $interface)
Also, interfaces do help with testing and decoupling code.
Type hinting in function/method signatures allows you to have much more control about the way a class interfaces with it's environment.
If you'd just hope that a user of your class will only use the correct objects as method parameters, you'll probably run into trouble. To prevent this, you'd have to implement complicated checks and filters that would just bloat your code and definitely have would lower your codes performance.
Type hinting gives you a tool to ensure compatibility without any bloated, hand written checks. It also allows your classes to tell the world what they can do and where they'll fit in.
Especially in complex frameworks like the Zend Framework, interfaces make your live much easier because they tell you what to expect from a class and because you know what methods to implement to be compatible to something.
In my opinion, there's no point, no need and no sense. Things like interfaces, visibility modifiers or type hints are designed to enforce program "correctness" (in some sense) without actually running it. Since this is not possible in a dynamic language like php, these constructs are essentially useless. The only reason why they were added to php is make it look more like java, thus making the language more attractive for the "enterprise" market.
Forgot to add: uncommented downvoting sucks. ;//
I have learned how to use classes in PHP and so far I have only really found one useful application for them. I created a user class to preform various tasks relating to users in my web application such as output the avatar, show number of messages ect.
Aside from this example, what are some other useful ways to utilize classes in a practical sense?
I use a database class all the time.
Here are a couple examples:
http://www.massless.org/_tests/phpdb/
http://slaout.linux62.org/php/index.html
http://www.tonymarston.net/php-mysql/databaseobjects.html
It's a really good idea to read other people's code and see how they have separated things into classes. Look at some PEAR modules or a framework ( Zend, Symfony, Cake ).
Any time you can define a 'thing' that 'does stuff', you've got a candidate for defining an object. Two concrete examples, from the PHP standard library, that immediately pop to mind are :
Numerous database modules use objects for connections, queries & results.
The DateTime class encapsulates a generic concept of time with input & output formatting, timezone conversions & date arithmetic.
The thing is, Object Oriented Programming is a big idea - you can solve almost any programming problem in an object oriented way.
I've built an utility class that humanizes the use of the mail() function, which I tend to use quite a lot.
By using classes (e.g. PEAR packages mentioned above, others), you are able to leverage code that has already been written and tested to perform common tasks.
Helps you to not reinvent the wheel, too.
I would highly recommend learning about [design patterns][1]. Many of them make good use of classes and solve common programming problems. In particular the Factory and Abstract Factory patterns are a good place to start.
There is also an excellent book called PHP Hacks that has a chapter about implementing a host of different patterns in PHP, so you might want to check that out.
Also, explore some of these built-in objects in PHP to see how they work and get more ideas:
PDO
ArrayObject
SimpleXMLElement
DirectoryIterator
[1]: http://en.wikipedia.org/wiki/Design_pattern_(computer_science)"design patterns"
I created a user class to preform various tasks relating to users in my web application such as output the avatar, show number of messages ect.
Check out http://en.wikipedia.org/wiki/Cohesion_(computer_science)
Your example sounds like Logical cohesion.
Aim for functional cohesion. Each class does a particular task, and make classes as generic as possible and you'll find you can reuse them over and over.
A great example of that, is Symfony's sfParameterHolder:
http://www.symfony-project.org/book/1_2/02-Exploring-Symfony-s-Code#chapter_02_sub_parameter_holders
Symfony uses it to hold variables for view templates (in a MVC), to store request parameters in the web request object (itself a class that represents all request parameters dutifully stripped of backslashes etc), in the sfUser class to store all the parameters that eventually go in the $_SESSION etc etc.
Download Symfony's "sandbox", go into the /lib/symfony/ folder and learn from it. It"s complex but the code imho is very clean.
http://www.symfony-project.org/installation
Zend is nice too, but the number of include files mayb be overwhelming and I am personally not fond of their naming conventions, in particular using underscore prefixes.