I'm novice for PHP object Oriented Programming and confuse in following
i have a class "Customer" (customer.php) which has methods "display_registration_form()" and "add_cutomer()". the method "display_registration_form()" has code for the form to echo in order to display that form.
when user fills and submit that form, i need to send the data to "add_cutomer()" method which has SQL to add that data to the database.
but how to call that function? in procedural way it is easy to send data to the script where the method is defined and then call the method...but in this the script has a class!
so i think to define an other PHP script something "add_cutomer.php", instantiate an object from the class file, then call the method "add_customer()".
**form ----> add_cutomer.php <--------- customer.php (class)**
this solution learns me that in implementing OO in PHP, create the class file and create separate file(which is not a class just instantiate an object from the class) when using method of that class. May i know that, is it the correct way to implement or is there another if this is incorrect?
thanking you
regards
pradeep
Try this method:
customer.php
class Customer{
function display_registration_form(){
// Here is your function
}
}
callfunction.php
$db = new Customer();
$registration = $db->display_registration_form();
echo $registration;
You might want to read up on the basics of object oriented PHP programming using some of the free tutorials available throughtout the net. Here are a few a good places to start:
http://www.php.net/oop5.basic
http://www.tutorialspoint.com/php/php_object_oriented.htm
Wow, if you intend to code using OOP, a class method is not a good way to do it, it does not comply with MVC, also you can not manage the output format and the used theme.
However, this is a good thing to create and instantiate objects with this class.
You should understand there is 2 types of methods in OOP, the class methods and the instance methods, the first ones is also called static methods in PHP.
http://www.php.net/manual/en/language.oop5.static.php
Then, make sure you understand that instantiate a SQL object and create it very different, you will have 2 different static methods.
Finally, there are many PHP frameworks that implements OOP in a good way, i advise you to use one of them.
Related
Ok, so I am building a web application relying on Zend PHP....
Before having to read everything to describe my nested functions, what I need is to be able to call a function from one class to another, which neither are extended upon another, are already extending a db constructor, which are all independently separate files called by one master initializing script .... (?) ... Thanks in advance, and there is a better example below as to what I mean.
My HTML Page calls a "master" include list which initializes and creates all the instances of all my classes so that all pages have common access to the functions. i.e. require('app_init.php');
Here is the most important excerpt of app_init.php:
require_once('class-general.php');
require_once('class-users.php');
require_once('class-identities.php');
$general = new General();
$users = new Users($db);
$iden = new Iden($db);
---class-general.php
$general is my basis for stupid common functions I use, as well as the DB constructor that all classes can be extended from.
----class-users.php
<?php
class Users extends General{
public function getUserID(){....random block of auth code.... return $randomID#; }
}?>
-----class-identities.php
<?php
class Iden extends General{
public function do_random_change_to_db($with_me){
....random prepared function using $with_me....
$this->logger->log("Someone with UserID: ". /*((?$this?) HERE:)*/ FIXME->getUserID() . " did something : ".$with_me ."." , Zend_Log::INFO);
$success="gucci";
return $success;
}
}?>
Right now, I am being tossed a PHP error for
Fatal error: Call to undefined method Iden::getUserID() in ...`
What would be the best way to go about this? I've tried to include one class file with the other one, but i dont exactly want to create a $FIXME= new Users(); either to save on memory space.
I also honestly would prefer to not extend any more classes off another at this time.
Thank you in advance.
If the getUserID method does not depend on any instance state (and it doesn't look like it does, though you haven't made it entirely clear), making it static will allow you to call it like so:
Users::getUserID();
If it does depend on instance state, you will need to call it on an instance of the Users class.
It seems to me that General's methods should actually be static as well, or perhaps even be free functions outside of a class. Remember: classes are used to encapsulate state. If there's no state that needs to be encapsulated, use class (static) methods or simple functions. Do not needlessly complicate your code by introducing objects and inheritance in which those paradigms don't make sense.
In my efforts to rewrite a past project of mine with OOP in mind, I have broken my code up into classes such as Devices, Facilities, etc.
Before moving to a more object oriented approach, I just stuck all of my helper functions in an included "functions.php" file. Using Devices as an example, would it be best to have a Devices class for my object specific properties/methods, then have a DeviceManager class to store functions like getDeviceByName, getDeviceByID, etc?
From what I am understanding, OOP is more about readability/manageability than anything else, why I assume the purpose would just be to have something like DeviceManager::GetDevice("Computer1") in place of GetDeviceByName("Computer1")
If you are thinking of using a class as a namespace then you can just as well use an actual namespace:
namespace MyCollectionOfFunctions;
function printMyName($name) {
echo $name;
}
And then you can use the functions like this:
use MyCollectionOfFunctions as fn;
echo fn\printMyName('Brett Powell');
There is nothing wrong with functions. Do not let anyone tell you that they belong is a class, as static methods. It can be done that way, but since we got namespaces there really is no reason for it.
In a OOP languages like C# or Java, you simply can't have functions outside a class, so there's no issue. That doesn't mean you're doing OOP, which is a mindset.
In PHP you can either put the relevant functions into a nampespace or within a class (inside a namespace). It's up to you, there's no right or wrong approach. Personally, I'd put them into a class because that's how I'm doing it in C# and it'll help a bit with productivity: I group related functionality in one place (class). It's easier to manage.
But strictly from a programming point of view, there's no difference, your code won't be cleaner/decoupled or more OOP because you've put functions into a class or namespace
A few advantages when using Namespace or Class for static functions.
Namespace and Class Name helps distinguish functions. You can avoid naming conflicts.
DPDate::FirstDayOfMonth() is better than FirstDayOfMonth() when you want to take advantage of auto suggestion of the IDE.
It is really all about cohesion and decoupling.
You must following this rules:
In OOP you MUST ALWAYS use a CLASS
Your method must have a single responsability
Avoid generic helper classes, classes must have a simple and specific responsability
Don't use static methods, use strategy (pass the object throw the param) to call a method, this way you can create a Mock to test your methods.
Avoid private methods, this make dificult to test your classes
Keep this things in mind, and you will gona make a clean code. =)
Answering Eric about item 4: This code it will use static method:
public function myFunction() {
$deviceId = DeviceManger::getDeviceId('computer 1');
// Rest of code using the device id
}
This way i cant mock the return of Device ID, this way i can:
public function myFunction(deviceManger) {
$deviceId = deviceManager->getDeviceId('computer 1');
// Rest of code using the device id
}
The code with mock in test function:
$deviceManager = $this->getMock('DeviceManager');
$deviceManager->method('getDeviceId')->returnValue(1);
myFuncion($deviceManager);
I wrote a wordpress plugin that works fine. However, it just works but there is no OOP here because at that time it was necessary to build something asap. I read some literature and found that php do not support multiple inheritance due to diamond problem.
Current scenario:
Flickr
--pic importer
----1. sql.php
----2. javascript.php
----3. call to show database contents
--photoset importer
----1. sql.php
----2. javascript.php
----3. call to show database contents
Here, I have created 2 class: picImporter and photosetImporter. Both classes share common contents from (1. sql.php and 2. javascript.php) but point-3 (implementation of showing database content is differnt for them).
So, my idea is: I should create another class Global and photosetImporter, picImporter class should extend this class. In the Global class there should be an abstract class that child class must define. So the design becomes:
Class Global{
//$sql comes sql.php,
//$javacript comes javascript.php,
abstract protected function showDatabaseContents();
}
Class picImporter extends Global{
protected function showDatabaseContents() {
//implementation using **$sql** from base
}
}
Class photosetImporter extends Global{
protected function showDatabaseContents() {
//implementation using **$javascript** from base
}
}
Before I proceed, I just want to know if I am on right track or not and further instruction if possible.
Thanks,
-S.
There's no particular "right" way to do what you're looking for (though there are wrong ways). Hard to know what method I would use without understanding what your javascript class does.
Typically, I create a single global DB abstraction class (what I assume your sql class is) and just access it from the global scope wherever I need it. Global scope isn't evil, especially for things like database access which aren't inherent to whatever other classes you're creating but are needed pretty much everywhere. The same may be true for your javascript class.
That said, if you need this sort of abstraction to maintain a consistent design in your application, then I see no problem with what you're doing here, this seems like a logical approach.
If you're looking for what might be a best practice, run a search for "PHP design patterns", but in general my approach with PHP is to keep it simple and accessible. That may mean using a design pattern, or it may mean a more basic approach, depending.
Ok I am trying to start really learning OOP style in PHP. I have declared both interfaces and classes and have the classes implementing the interfaces. I was wondering however, is it not possible to just load interface files in into PHP script files and call the methods from the interface instead of loading the class implementation files? If so, how would that be done b/c I cannot find an answer to this. Thanks!
Interfaces can have no implementation, so you cannot do that. Their purpose is to stipulate "contracts" (in the sense that "classes that implement this interface promise to provide public methods X Y and Z") that the classes (which implement the interfaces) must honor.
This is really really basic OOP stuff, and it's not applicable to just PHP. I would suggest studying some more OOP theory before you try to progress further.
You cannot call methods on an interface. An interface cannot be instantiated. You must create a class that implements the interface and use that class instead.
An INTERFACE is provided so you can describe a set of functions and then hide the final implementation of those functions in an implementing class. This allows you to change the IMPLEMENTATION of those functions without changing how you use it.
For example: I have a database. I want to write a class that accesses the data in my database. I define an interface like this:
interface Database {
function listOrders();
function addOrder();
function removeOrder();
...
}
Then let's say we start out using a MySQL database. So we write a class to access the MySQL database:
class MySqlDatabase implements Database {
function listOrders() {...
}
we write these methods as needed to get to the MySQL database tables. Then you can write your controller to use the interface as such:
$database = new MySqlDatabase();
foreach ($database->listOrders() as $order) {
Then let's say we decide to migrate to an Oracle database. We could write another class to get to the Oracle database as such:
class OracleDatabase implements Database {
public function listOrders() {...
}
Then - to switch our application to use the Oracle database instead of the MySQL database we only have to change ONE LINE of code:
$database = new OracleDatabase();
all other lines of code, such as:
foreach ($database->listOrders() as $order) {
will remain unchanged. The point is - the INTERFACE describes the methods that we need to access our database. It does NOT describe in any way HOW we achieve that. That's what the IMPLEMENTing class does. We can IMPLEMENT this interface as many times as we need in as many different ways as we need. We can then switch between implementations of the interface without impact to our code because the interface defines how we will use it regardless of how it actually works.
I was wondering if there is any major different in the following, and whether one is more 'standard' than the other:
<?php
class Account extends Database {
public function myMethod()
{
// Do something
}
}
?>
or
<?php
require('database.class.php');
class Account {
public function myMethod()
{
// Do something
}
}
?>
Cheers :)
Edit:
This question actually relates to a tutorial series I have been following which describes the above two methods - which didn't make any clear sense.
So thank you for the constructive answers on clearing that one up!
Those are two completely separate language constructs.
Your first example deals with inheritance. Basically, you already have a class called Database, but you want to have a specialized version of that class to handle accounts. Rather than build a brand new Account class and copy/paste all the functionality you already have in your Database class, you simply tell PHP that you want to use the existing Database class as a baseline. You create any account-specific functionality in the new Account class, and anything database-related comes automatically. This is assuming, of course, that you have some way of specifying where the Database class is defined - for example, a require declaration at the top of the class, or an __autoload() or spl_autoload_register() function call defining a way to find and locate the file containing the Database class.
In your second example, your database-related code is completely separated from your Account class. They're completely distinct entities, and if you wanted to do anything database-related in your Account class, you would have to explicitly instantiate a new Database object within that class (or pass it to that class, or one of its functions, as a parameter.
Basically, extends helps define what a class is, whereas require shows where a class definition (or other code) is stored.
Both code snippets aren't even equivalent.
The first declares Account to extend Database, a is-a relation.
In the second code snippet, you are simply saying that you require 'database.class.php' ... and that neither has anything to do with OO, nor defines a is-relation from Account to Database.
Both are completely different in first one class is inherited by another class but in the second one the class is included in your script only.
Means if you extend all the public and protected methods are available in your derived class and you can create object of derived class and can use methods with derived class's object.
But in the second method the class is included in your script and require this class it's own method and work independently.
The first means you create a new class, which has all the functionality of Database class and those you implement.
The second means that you create a new class, but it doesn't have Database functionality since it's not extending it. If you need database access in your Account class, you can create an instance in constructor, or pass already created instance as constructor parameter.
It's hard to say what is more standard, since it depends on what You actually want to achieve.
To put it in most simple terms:-
require or include is structural programming.
extends is object oriented