Discuss Another question regarding coding in a smart way? in the PHP Development forum on Dev Shed. Another question regarding coding in a smart way? PHP Development forum discussing coding practices, tips on PHP, and other PHP-related topics. PHP is an open source scripting language that has taken the web development industry by storm.
Time spent in forums: 2 Weeks 4 Days 8 h 3 m 24 sec
Reputation Power: 369
Another question regarding coding in a smart way?
My company creates Landing pages for clients. The details are sent to our system through an API. Now I am re-writing code to make it more efficient as previously it was all over the place..
Here are my two thoughts:
1. have separate files... 1 for creating XML (as they vary between landing pages), 2. another for connecting to the API and then include them
2. bundle this all up in a class? ie a function that would create the xml, another for validating, getting errors back etc..
I think i probably answered my own question, it should be 2. but wrapping API connect call in a class? is that a bit of an overkill? because that API (which has methods etc) returns errors and all the other things.. this is why 1) sounds better because all the code will be included without me calling the AP in each page?
on another note: I would like to "document" the code so the structure of the site is easier for the new person.
Time spent in forums: 4 Weeks 8 h 19 m 58 sec
Reputation Power: 4123
I take the approach that I have one class to do one thing and I only put one class in a file.
If a class grows beyond 50 lines of code (not a hard and fast rule) then I look for ways to abstract out the code I've written.
Eg is one method so long it takes over....could it be moved into a "library" or "tools" function?
Eg do I have so many methods that some could go into an abstract parent class or trait (php 5.4+).
I expect your API is some sort of data service, which will offer some sort of basic Create Read Update and Delete (CRUD) functionality - just like a database. so I'd look at a common interface for data services, then implement these for an APIDataService, MySQLDataService, etc - then all the method names/arguments are the same but the implementations are different....so wrapping these up does make some sense.
Have a front-controller or router which accepts all requests and calls the appropriate action classes. Have a read up on Dependency Injection if following this approach
Look at autoload (preferably spl auto load) to help with your file inclusions
Consider namespaces (php 5.3+) if your the number of files you have is large or semantically broken down, eg
Class: \data\Service - this would be an abstract class which implements the dataService interface
Classes:\data\Services\API, \data\Services\MySQL - these would be concrete classes extending the \data\Service class, implementing any remaining methods