Using PHP Classes for Device Objects - php

I have developed a Web Interface for managing our devices (Dedicated Servers/Switches/etc) at work, however with my basic PHP knowledge, I ignored OOP completely. In the current state it just queries the MYSQL Database and populates the tables. Functions are all stored in a Functions.php file and called as needed.
As the project is functional and used now, I would like to rewrite this to be more efficient as it will be used among our other brands. I am having trouble applying the concept of classes to this project though (I use them all the time in C#/C++).
The way I see it, each Device be it a server, switch, etc. could be a part of a Device class that keeps properties like Datacenter, Name, etc. and methods such as Update, Delete, etc. I suppose I could additionally have a base Device class, then subsequent classes such as Server/Switch/etc. which inherit from that.
My question then is how is this more efficient? Each time the page loads I am still going to have to generate each instance of Device and then populate it from the Database, why I don't really see how this is better than the current implementation.
Thanks for any insight!

Using OOP is mostly unrelated to performance or efficiency. However, it allows you to organize your code in a modular fashion, and encourage code reuse.
A better webpage to explain can be found here.

Related

Am I using oop wrongly?

I started learning oop about 6 months ago, although I stopped for a while because of studies.
The problem is that whenever I use oop in my project I usually try to just make every single thing a class... Whether intialization, displaying, looping and much more... to be precise, I haven't gotten the concept of when to use/create classes.
Another problem is that I tend not to know the major benefit of a classes over a functions . Currently, I just mix them up.
I watch a youtube video that talks about classes and client code. In that video they said that classes are more of like developer codes while client codes are codes we write which uses the developer code to make things easier. So he advise we break our code to client/developer code.
But I don't know how to break my code into client code and developer code.
Infact at a point I was creating classes for all my pages like index.php, about.php
<?php
class about{
public $title = 'about page';
public $page_color = 'red';
//functions and more codes
}
After writing the above code I know I am not doing something right. I have tried to search google and have read many oop books but each time they use the car class example which I can not apply to my coding or just wouldn't address the context were a class is or isn't necessary.
Note: I am comfortable building website using procedural codes but I need to learn oop incase I need it someday.
To answer your question: Yes you're using it incorrectly. However it's not a quick fix to get you using it correctly.
There isn't an answer I can give you that will mean you start writing perfect OOP code tomorrow.
You're on the right path, study and practice. Make mistakes, live with those mistakes and refactor them. You'll get sharper the more you do this.
I'm at 16 years experience and I still find new rules and exceptions in OOP. It's not an exact science - it's a method that can yield different results depending on the context.
Just look at all the comments you've had and you'll see no general perfect consensus. Everyone is iteratively improving each others implementation. You can use this approach in your code, keep it tidy and organised, swap bits out as you find better or more correct ways of implementing them.
Well I have not learned php. But I am a good Java developer. And my OOP concepts are good. You mentioned that you do not understand major advantages of classes over function. Both of them are totally different. A class is a blueprint of software.Where as a function represents behaviour of software. You write all the code that does the processing of data provided as input by user and generation of output in functions. Classes contain these functions. The major advantage of writing code in classes is that they can be written in one place and reused anywhere. And OOP concepts are too vast. Each and everything cannot be explained in posts. OOP is much more advantageous than procedural-programming. Consider you are working on a very big project. Some features in the software are common. In OOP you can write code in one place and use them wherever you want.Whereas in procedural-programming you have to rewrite the same code wherever you are using those features. So, your headache of writing code will be minimized in OOP. Also, if the common code works on one place it will obviously work wherever it is being used. This is how OOP evolved from procedural-programming.
OOP is the backbone of most programming languages so you will want to use it basically all the time when you have it fully understood.
Websites are a little trickier to give you good examples of so I'll try and give a generic outline and then a more web-based focus.
Classes should hold data that is related to each-over in a common sense name. For example a Car would obviously hold the Engine (another class), the colour, the name, the owner, etc. And within that the engine would hold it's own set of data that is relative to it (max speed, miles per gallon, etc.). This is the basis of holding your data together, next comes functions within classes.
Now while Car holds data relative to the car, Car also holds functions that the car would do, or functions that the car will use to interact with it's data. Getters(GetColour()) allow outside objects to get information about that specific car (as Car1 and Car2 could hold different colours). Setters are the opposite, to set object specific data. Then we have everything else. Car.start() which internally calls this.engine.start() which may set up some functions to start draining gas from the engine and allow the car to move.
Classes are all about having this easy to read, easy to understand, and easy to re-use. Once your Car class is complete you can re-use as many cars as you need and they are all nicely self-contained.
On to web
Firstly, I highly recommend you look into MVC architecture, which is where the bulk of web architecture is and makes OOP easier to understand for web. Basically your website is split into controllers (in charge of interracting with the DB and giving you back the page), models(Your database data, e.g a user) and your views (HTML with a little templating so your controllers can pass it dynamic data)
For example: You go to website/posts/Stanley , Your Router (another MVC thing) decides that this needs to be handled by the PostsController(a class). The posts controller knows that you want all posts by user Stanley, so it asks the Posts Model(a class)to retrieve all posts by Stanley, the controller then passes these to the view to fill out a template using your Stanley specific posts.
Going away from MVC a second,
With your example given, you will mostly use classes, I would assume, for data manipulation and DB access. For example if you stored blog posts in a database you may have a class Blog with data that matches your db rows (id, user_id, title, body) and functions to access that data to put in your HTML, but also to grab that from the database easily.
For example:
BlogPost::All() may return an array of every blog post newest to oldest.
BlogPost:By(user_id) may return an array of posts by a specific user.
BlogPost:Remove(id) may remove the blog post given it's id.
BlogPost:RatingAtLeast(starRating), get all blog posts with atleast a starRating rating.
You get the idea... This class would exist as you said above, to give you a client code way to access your database that is SPECIFIC to your use case and as BlogPost contains variables related to your BlogPost. So BlogPost::All() will return an array of BlogPost.

I have been writing PHP without "classes" for years... what am I missing?

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.

Theory/Magic behind creating API

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

Use common functions and views for web database applications

I have a design discussion with a collegue.
We are implementing a PHP MySQL database application. In the first instance we have written the Insert Get Update Delete, SelectAll and Search functions for a particular table, writting the table and fieldnames in the code, with several php files, one for the object class, one to draw the HTML table for that table, one for editing a row of that table, one containing the above functions, etc.
The disagreement comes as I have now written generic functions that read/write from the database and draw the HTML taking the table name as a parameter, letting these functions discovers the fieldnames from the database or class. So now that code can be used for any table, with any fields without having to manually go in change each function that needs alteration. I understand there will be cases where more table specific functionality is needed, and this I think that should be done as requirements arise, integrating common parts where possible.
My collegue on the other hand is adamant we should keep a set of files separate for each table, i.e. around 5 php files for each table. The read/write functions written differently in each case, with the need for any changes required for all tables to be affecting 5 x number of tables amount of times.
I can certainly say there will be more than main 15 tables in the database that will at least need basic funcionality.
What approach do you think is most appropriate?
One of the important principles in programming is DRY : Don't Repeat Yourself. So, everything common to several usecases should be written once, in a single location.
Now, I've never had to develop an application where each database table had the same, generic, crud pages. If it were the case, it wouldn't be a functional application, but a database management application. Are you sure you aren't redeveloping phpMyAdmin?
If you need the same code to handle several base operations on several tables, I would say you shouldn't write that code more than once : no need to repeat yourself :
it would take more time writing the application
it would take more time (and possible cause more bugs) when maintaining it
A possible solution could be to put as much common code as possible into a single class, common to many tables ; and, then, have a specific class for each table, that would extend that common class.
This way :
The common code would be written only once
Each table could have its specific code
The common code could be overridden for a specific table, if necessary.
About that, see the Object Inheritance section of the manual.
About that common class idea, you could even go farther, and write pretty much no code at all, if your CRUD is generic enough : there are ORM frameworks that might do that for you.
For instance, you might want to take a look at Doctrine.
We're on the first stages of development, and we don't have the complete functional specifications for the web application we're developing. Yes, we know, but it's not our fault.
So, we're building some parts keeping them pretty simple and straight-forward so we can build on top of that when we have more details on what to build.
We have a section for clients, for ads, for users, ... and I wanted to keep things separate because we don't know what's coming in the future. Yes, at the moment we have only a few fields and some basic listings and editing pages, but all that will grow.
It's not that I don't want to implement some generic code that we can reuse. It's that we don't know yet what will be the limitations in the near future, and I don't want to write generic code that we'll have to parametrize intensely.
For example, Alex built a generic Update method to which you pass an object and it will create an UPDATE SQL statement and execute it. OK, that's cool, but that doesn't work for the Users section of the web app because we store the password encoded. First, it won't encode the password. Second, if you edit a user and don't enter anything on the password and password-confirmation fields, the old password will remain. So, we have a problem with the generic Update method, and as I see it there are two possible solutions:
a) Parametrize the Update method so if it is modifying a user, keep the password if the password on the object is blank. And encode the password, of course.
b) Override the Update method for the child class.
Alex's implementation didn't use inheritance and he used the generic methods in a static class he'd call this way DataAccess::Update($object);. The method takes the table name from the class name as he modified the database to make them match (I prefer "Clients" for the table and "Client" for the class). So, option b is not possible with Alex's implementation.
The way I was trying to build it was keeping separate Update methods for each table. Yes, I was repeating myself but, as I said before, we don't have a full specification, so we don't know how it's going to grow. We have an idea, but we don't have the exact details.
So, the point here is that I don't want to write generic code until we have a much more detailed specification so we can evaluate what can and what cannot be shared between the parts.
Not all sections of the web app work the same and, as JB Nizet said: "If it were the case, it wouldn't be a functional application, but a database management application."
And I can tell you for sure this is not a database management application, even though Alex would say "we're just building a database app." Well, maybe, but a database application is not only showing/modifying the tables. And now, views won't solve all problems.
Again, as JB Nizet said: "If it were the case, it wouldn't be a functional application, but a database management application."
And now I'm repeating myself again, but this time there's no reason for that.
Thanks for your time.

What is the Best Workflow for Web Application?

I am about to begin a web application. Before I begin, I would like to get some advice as to what the best work flow/order is for creating a web application such as this.
My project will consist of a server-side with PHP and MySQL. The client-side will be XHtml, CSS and jQuery. There will also be AJAX used.
I'm sure that it can depend on certain situations, but, overall, what is the best order for developing a project with these credentials?
Should I start developing the server-side first? Or should I begin with the client-side? Or should I do both at the same time? What about the database - should that be a first priority? Then perhaps the DAOs?
Start with the data first. The server-side data is the persistent, essential core of the application. If this data model isn't right, you have nothing.
You should be able to unit test the data model to prove that you have the right attributes and relationships. This doesn't require much. A few test cases to insert, update and query.
You will support that data model with back-end processing.
This, too, should be unit tested to demonstrate that it works and does all the right things to your data model. This will be a bit more complex, since this processing is the application.
Then you can think about the data model as exposed by web services to Ajax.
This, also, is testable to prove that the JSON does the right things. This testing is often fairly complex because this is what the GUI front-end relies on. This has to be right.
Then, once you have that Ajax data model worked out, you can write the front-end GUI.
The workflow you're describing is what I use for my own (solo) projects.
I like to meet in the middle. I do data modeling first, and simultaneously start prototyping the interface. Business rules come last and pull everything together.
I also find it "inspiring" when I have a GUI to look at... it encourages me to make it do something. Furthermore, GUI's tend to undergo the most revising, so starting them early in the process ensures you'll be happy with the finished product, and that it'll be finalized by the time your business logic is implemented.
If I'm working for a big company that's not sure of exactly what they want, I'll start with the UI first. This way they get to figure out what they want before I've put a lot of time into the rest of the system.
On the other hand, if I know exactly what is needed, then I will start with one feature and work my way up through the layers, database, controller, view, and ajax, until that feature is done, and then go on to the next feature. This way I've got less context to remember, and the client always has something new to play with.
I can't tell you what's absolutely best, but what works for me is...
Talk to the business people to get an idea of what they want.
Draw the UI with pen and paper. Boxes represent pages. Buttons and links have arrows pointing to other pages. Don't need every microscopic detail. Some things are implicit.
Once the UI is mapped out pretty well, design the DB schema. Sometimes I'll write out all the tables in a text file like this...
pets
----
id
name
species
# etc...
Then implement the database. I use Rails migrations. You might write the DDL manually.
If you have models or DAOs or something along those lines I would implement those next, with unit tests.
Then I usually work through the app entity by entity. Get the view and controllers working. Rapidly switching between the testing code and the implementation code.
That's the general sequence, but the whole time there are adjustments and so on. You'll need to go back to your DB design and evolve that as you build the actual functionality.

Categories