I am learning about design patterns. Currently I am working on a web service and I have time to structure the code, where I want to implement some design patterns.I already do watch to have each class doing one related thing, and write small functions with one or two parameters, but when it comes to design patterns, I am stuck.
My application is getting the data from external api, users, organizations and jobs. I have created these three classes, and currently they are all containing almost same curl call, same curl options and headers. And each of this class have one function, for organizations - getOrganizations, for users - getUsers ... Which all have same body, just a different curl call.
So I need just a reference, to a design patterns that can help me structure maintainable code.
From reading your description you just need to practice OOP a bit more. (object oriented programming).
In this given example you could make a function that accepts the URL and either make all your requests extend from that base class that has that function 9r make a utility class with the curl logic and simply use that.
Also there are a ton of good php curl plugins on composer which can help you.
Related
This question is a bit hard to explain, but I'll try my best.
Say, I am creating an job add aggregator site. For this, I have 10 job sites I will crawl through, parse the HTML
and get all the juices.
Now, since each sites template, url and the amount of information they contain is unique, something tells me the crawling part
should be organized separately.
Normally, I could put it all together in
class CrawlerController extends Controller {
public function fooDotComAction(){
}
public function barDotNetAction(){
}
}
You can see the above is still better than dumping all my crawler logic inside the DefaultController,
but even my example doesn't seem efficient, or modular.
It seems like a bad practice, I am wandering if there is some sort of feature in Symfony that
provides an implementation or guide for such problems.
Your question is too broad but you have find the design pattern who will fit your needs then implement it. You will need to create php class and to declare them as services.
Symfony promotes the ideas of service-oriented architecture and has powerful solution for separation of concerns: The Dependency Injection Component. In short, this component provides implementation of the Service Container: a tool for configuration, binding and creation of the separate service objects.
Your business code will be contain in domain services and your controller will just organize the input and output and call the domain services
check out https://codereviewvideos.com/blog/symfony-compiler-pass-tutorial/
and the 2 linked videos and explanations. (1, 2)
it will show you how you can, in a clean way, seperate each 'crawler', using tagged services and a compiler pass, which i think would be a clean way of doing this .
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.
Im a newbie PHP programmer and I have a few questions about creating a REST based API service.
Basically, its going to be a github open source project which is going to scrape various data off the web and offer it as an API in XML. Now here are my questions in terms of how should I or how can I do this.
1) Since there isnt a robust/same pattern for getting various data through scraping, what is the best way to actually output the xml?
I mean the PHP file would have various lines of extracting data from various points in the code and the file would be a lot of lines. Is it a good idea to type the code to output the result in there?
2) Is there a way to organize the scraping code in a sort of class?
I cant think of a way that would work besides linear approach where not even a function is created and you just apply functions (in general).
3) If theres a way to do that ^^ , how can it you output it?
Is there any other approach besides using another file and getting the contents from the main file and displaying the code through the secondary file.
4) If I were to offer the API in XML and JSON, is there a way to port from one result to another or will I have to manually create the fields in json or xml and place the content in there?
I might have more questions that might arise after these have been answered but I hope I get everything cleared up. Also, this is assuming that the results are not fetched from a DB so the data has to be scraped/tabulated on every request. (even though caching will be implemented later)
Thanks
This question is probably more appropriate on https://codereview.stackexchange.com/
Not to be rude, but a newbie programmer developing an API is like a first-year med student offering to do open-heart transplants for free. I understand that you believe that you can program, but if you intend to release publicly accessible code, you probably need more experience. Otherwise guys like me will muck through it and file bug reports ridiculing your code.
That said, if you want theory of good API design you should probably check out Head First Object Oriented Analysis and Design. You'll want to focus on these key concepts
Program to an Interface, not an Implementation
Encapsulate what varies
...and follow other good design principles.
...honestly, there's a lot to cover to good interface and good systems design. You can use this as a learning exercise, but let people know they shouldn't rely on your code. Though they should know that screen scraping is far more brittle and instable than web service API requests anyway, but many don't.
That said, to provide some initial guidance:
Yes, use OOP. Encapsulate the part that actually does the scraping (presumably using cURL) in a class. This will allow you to switch scraping engines transparently to the end user. Encapsulate your outputs in classes, which will allow for easy extension (i.e. if JSON output is in a Single Responsibility class and XML Output is in another, I can add RSS Output easily by making a new class without breaking your old code)
Think about the contracts your code must live up to. That will drive the interface. If you are scraping a particular type of data (say, sports scores for a given day), those should drive the types of operations available (i.e. function getSportsScoresForDate(date toGet))
Start with your most abstract/general operations at a top level interface, then use other interfaces that extend that interface. This allows users to have interfaces at different levels of granularity (i.e. class SensorDataInterface has a method getData(). HeartRateMonitorInterface extends SensorDataInterface and adds getDataForTimeInterval())
In my company we have developped some applications. We have to create an API for one application (say application A), so that the others can use it (an its data).
The question is : we already have developped PHP classes for the model of Application A, if we want to create an API, should we :
- re-use these classes (too much functionnalities for an API, too heavy...)
- create one PHP class, with some basic functions, that takes in input and returns only raw values (like strings, array... NOT complex classes)
- create another set of PHP classes, simpler, and designed only to be used by an external application (so only to get data easily)
Usually, an API is the 2nd solution (to be used as well with PHP than as a web service for example), but i find it too bad that we made a complex and usefull class modelisation, then we tear it apart just to have functions, strings and array.
The 3rd one seems to me to be the compromise, but a collegue of mine insist that this is not an API. Too bad...
What do you think ?
Solution number 3 might be the best one from an architectural point of view. Basically you are using a Facade Design Pattern to simplify your API. Since I am dealing with it at the moment: In Patterns Of Enterprise Application Architecture this approach is described as the service layer which makes totally sense since you don't want to expose any user (meaning whoever will deal with your API) to more complexity than is actually needed or desired.
This includes using the easiest possible interface and transfer objects (raw values if they make sense). As soon as your Facade is being called through remoting services (like a webservice) you will eventually have to break repsonses and requests down to raw values (data containers) anyway.
Build a set of Facade classes that simplify the public API.
Create some thin wrappers that implement simpler API over the original classes. DO NOT reimplement any business logic in the wrapper - that'd lead you into trouble if any of the logic changes, as you will surely lose track of which piece was modified and which was not. Keep the external inputs/outputs simple, if you need something more complex than string, use XML or JSON for structured data, but try to avoid too much complexity - if you have 2 things to pass two query parameters might be much better than one structure with 2 fields.
That's the 'Facade' pattern.
I would also say have a look at the Facade pattern.
Build a set of Facade classes that only offers the functionality that is really needed to be public. Those classes then for sure use your current core classes.
This gives you also the advantage that if you change the core classes, the API must not necessarily being changed.
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.