Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I am learning Classes and OOP and PDO and all that stuff ( I know legacy php, so, can write php 4.x scripts with messy code ^^ ).
So, started to transform over my base template system to the new code
so far so good, sessions and PDO are in classes , pagination system is in a class, users are in a class (basicaly everything).
Here's my question.
I use 2 functions to do a single thing
first function is to get the user rights and it looks like this
function u()
{
if ($_SESSION['loggedin'] == 1)
{
return true;
}
else
{
return false;
}
}
As you can see, it just return true or false based on session (code contains more but is for admin/staff ).
Should I also convert this to a class ? or is it useless ? and leave it as a function ?
Then my second function is to get some arrays ( used for group system)
function arr($string, $separator = ',')
{
//Explode on comma
$vals = explode($separator, $string);
//Trim whitespace
foreach($vals as $key => $val) {
$vals[$key] = trim($val);
}
//Return empty array if no items found
//http://php.net/manual/en/function.explode.php#114273
return array_diff($vals, array(""));
}
As this function is only used for the group update and to get info from what groups users are in is it in a function
So my question,
as far as i understand OOP does it mean that you write code to make things 'easier', so should I also make a class of those functions to make things easier or is it useless as it makes it harder ?
if (u())
{code code};
if (a());
{admin code}
vs
$u = new User;
if $u->rank(user){
code code
}
if $u->rank(admin){
admin code
}
Base code can be found here
it is to give a idea what I am rewriting to pdo.
Should i rewrite a simple function to a class?
Will this make your code maintenance easier?
Is this function occuring on more than one place in your project?
I can't give you an absolute answer, however generating an Object Class in PHP for a static simple function is overkill. It means you need to write more code, and your PHP processor has to do several magnitudes more work for the same - simple - outcome.
If your function occurs just once in your project then NO, you do not need to classify it in any way. This just adds overhead.
But, if you are using this function across multiple scripts and especially if there is a reasonable expectation that this function might need editing/extending in the future, then following Don't Repeat Yourself programming means you could put this function into a Static Class.
In the context of this question I will say more about Static Classes below but other options to remove repetition could be having functions in an include file at the top of your script, this essentially does the same thing as a Static class.
Follow DRY and you can happily copy/paste your function into a Static Class and call that class as required.
Static Classes are not instantiated, and can be used as containers for abstract functions such as the one you are describing, which don't fit neatly elsewhere.
however, there is no conclusive answer without us knowing what you're expecting to do with your project, are you maintaining and developing this or just updating a project without adding new functionality?
There seems a large minority of people obsessive that everything needs to be in a class, regardless of efficiency. Resist this temptation to wrap everything in classes, unless:
Does it make your data management easier to modularise?
Does it reduce/remove code repetition?
Does it make your code easier for you to understand?
Static Class Example:
class StaticClass {
public static function u() {
return $_SESSION['loggedin'] == 1;
}
}
Usage:
StaticClass::u(); ///returns boolean.
To be honest your function is so simple that in this specific instance you might as well just code the if statement directly:
if(u()){
// runs if u comparison returns true
}
becomes:
if($_SESSION['loggedin'] == 1){
// runs the same comparison as u() but avoids the
//function/class overheads
}
One day, suppose you decide that you wish to handle both session and token based authentication.
interface AuthInterface
{
public function isAuthenticated(string $credentials): bool;
}
class SessionAuth implements AuthInterface
{
public function isAuthenticated(string $user)
{
return $_SESSION['loggedin'] == 1;
}
}
class TokenAuth implements AuthInterface
{
public function isAuthenticated(string $token)
{
// validate token and return true / false
}
}
So in above example, using classes is very handy. You can now switch out your implementations super easy - and your code should still work.
Writing classes and programming to an interface - enables you to depend on abstractions, not on concretions. It should make your life easier.
If you have a few functions that are like helpers - e.g a custom sorting function - then go ahead and keep as a function. No point going overboard.
I think you should be consistent in what you do, but if a function is really just something like
function u()
{
if ($_SESSION['loggedin'] == 1)
{
return true;
}
else
{
return false;
}
}
or if you make it short:
function(u) {
return $_SESSION['loggedin'] == 1;
}
There is no reason to create a class for a one-liner. Also some inprovements for your arr() function: If you want to apply a callback to all Elements of an array, use array_map()
function arr($string, $separator = ',')
{
//Explode on comma
$vals = explode($separator, $string);
//Trim whitespace
$vals = array_map("trim", $vals);
//Return empty array if no items found
//http://php.net/manual/en/function.explode.php#114273
return array_diff($vals, array(""));
}
It's good to move things into classes, it enables reuse and also you can use an autoloader to only load in the classes you're actually using, rather than PHP parsing all the code. I'd put the first function in a User class or something (pass the session information in as a parameter, don't access that from inside your class) and the second one maybe in a Utils class or something like that?
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I learning a bit of OO PHP but the docs I came across showed a couple of methods of the following examples. I am confused as to why both work, and which should be used exclusively.
I know that #1 is not OOP but I was still curious about the second method of echo, and if it should be used or not.
Both of the echo's below print "Lansana", but one initializes $name before the echo whereas the other initializes it after (or during) the echo.
<?php
$name = "Lansana";
echo $name;
echo $name = "Lansana";
?>
Notice how there is a public property $name with no value in the first example, and no public property in the second, yet both still work the same.
class Pets
{
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$dog = new Pets("Buddy");
echo $dog->name;
class Pets
{
public function __construct($name) {
$this->name = $name;
}
}
$dog = new Pets("Buddy");
echo $dog->name;
What is the preferred method in #1 and #2, and why? I don't know why the docs showed the first class method because I don't see the need for a public property there, but then again what do I know.
Thought I should give a little more context to what I outlined in the comments above.
For the First example try not to mix assignment and output in the same statement. Although it is syntactically correct it doesn't immediately indicate the intent of the statement.
For the second example as I stated in the comments explicitly defining properties is always preferable. The advantages are:
Most IDE's will auto-complete defined properties for you minimizing the risk of mistyping a property.
It clearly indicates to someone reading the code what properties are available on the object.
It allows for you to set the visibility of the property so you can control more how your class is used which promotes encapsulation.
One of the most common bugs that you see with OO PHP is when you silently create a property for example something like:
class A {
public function setUserId($id){
$this->userId = $id;
}
public function getUserId(){
return $this->userid;
}
}
The intent is clear here but you have to be paying pretty close attention to the fact that the referenced properties are cased differently. If becomes much harder if you throw in another 50 lines of code and the two property references aren't on the screen at the same time.
On of the uses for PHP's magic __get and __set method are to help eliminate this problem earlier in development. Example:
class A {
public $foo;
public $bar;
public function __set($prop, $val){
throw new Exception ($prop." does not exist on this object");
}
public function __get($prop){
throw new Exception ($prop." does not exist on this object");
}
}
This makes it where if you attempt to access an undefined property the class will throw an exception letting you know exactly what happened and where.
I think #1 is just a shortcut. #2 is because of overloading, where class variables are created dynamically.
http://www.php.net/manual/en/language.oop5.overloading.php
As for preferred methods, with #1 'echo $name = 'Something'` more of a short cut than a different method. The end outcome is the same in either case.
With #2, dynamically created variables are not usually a good idea as it can generate some unexpected results but they do have their place. Check the link above for some example of code using overloading. The first method is favored.
1
echo $name = "Lansana";
PHP interprets it as
echo ($name = "Lansana");
echo sort of works like a function, because of that php interprets everything on the right side of the echo before sending it to standard out.
2
The first one is definitely the best way. Because PHP is a dynamic language (as opposed to a static language like C# or Java) it allows one to create and set variables without declaring them first. It is the best to always declare class variables--it makes the code easier to read and maintain.
I am trying to write class code that can dynamically load external function code
to use as methods of the class. I understand that I could use extends and create
child objects, but it seems there would be a simpler way of going about this.
The point is to limit to bare essentials the amount of code that has to be
used to perform a particular function. And keep all the function code in separate files
that can be required.
class _DEMO
{
public $_addOn = '';
public function __construct()
{
require_once('DEMOAdd.php');
$this->addOn = addOn;
}
}
In DEMOAdd.php:
function addOn($_input)
{
return 'getting '.$_input;
}
How would I load this into the _DEMO class? The above produces fatal error.
print $_test->addOn('something');
In JavaScript it is possible to assign a function to a variable. I realize this
is not JavaScript, but I suspect there is analogous functionality in PHP.
I am also aware of variable variables in PHP but I am having trouble wrapping my brain around that concept.
In response to this advice
When another developer looks at your code it is just not clear what the particular role of this class is. Instead he has to inspect many files and external functions referenced in the class. It just would be better if he could take a look at the class and see "oh, that class does this and that". That's even a central aspect of object oriented programming.
I agree with you on this. I am working on a project that I am the only developer of everything, html, javascript, css,
and php. I have been using class definitions lately, but have written lots of procedural code in the past. The current
project has code that is sectioned off into several class def files so code can be reused in different contexts. My
consideration is if a query from a web page only needs 500 lines of code, why load 1500 lines of code to service the
request. Additionally, this is a cms system with a very limited amount of users (only me at present), so the volume
of traffic is not an issue. But if there was a larger user load, for each user extra code is required, thus the amount
of server memory require increased significantly. The cms web interface is to manage content that direct revision of code
would be very difficult. Yes, I am reinventing the wheel. So has Firestone, General, Nokian, etc etc etc.
Thank you all for the answers
I think I have the answer in anonymous functions that can be assigned to variables, re the php manual
$_var = function($_input)
{
return "getting ".$_input;
}
print $_var('something'); // I have to look back at the manual to varify this line's syntax... yep it looks good.
By using inheritance. You can extend the _DEMO class like this:
class _DEMO_ADD extends _DEMO {
...
function addOn(....) {
...
}
See docs on extends.
Designing the application properly
First of all. What you're trying to do violates fundamental aspects of clean object oriented design. Why even use a class when it's only purpose is to call an external function? If you want to proceed with it stick to functional programming.
The point is to limit to bare essentials the amount of code that has to be used to perform a particular function. And keep all the function code in separate files that can be required.
The attempt of good design is not (only) the amount of code you write, but rather how a certain task is achieved. If a class is suitable for solving your problem then use a class.
When another developer looks at your code it is just not clear what the particular role of this class is. Instead he has to inspect many files and external functions referenced in the class. It just would be better if he could take a look at the class and see "oh, that class does this and that". That's even a central aspect of object oriented programming.
Okay. Enough for off-topic. Since you ask especially for that certain problem I'll give you a few advices on that altough I don't recommend it and would advise to rethink your design.
Dynamic method calls
To call a function that has been defined somewhere else we will make use of the magic method __call($methodname, $args). This method will be called whenever you try to access classes method that does not exists.
Within this __call() method we will check if a function with the name of the method exists, we were trying to call. If not we can throw an Exception, otherwise we're going to execute the function using call_user_func_array().
functions.php
<?php
function addOn($input){
echo "This function is procedural and takes the param: " . $input;
}
MyClass.php
<?php
class MyClass{
// This will get called whenever a method on this class
// is called that does not exist
public function __call($name, $args)
{
// Let's check if a function called like the method we wanted
// to call exists somewhere
if(!function_exists($name))
{
// No? So let's raise an Exception
throw new Exception("The function you called " . $name . " does not exist");
}
// Such a function seems to exist so call it and pass
// the arguments
call_user_func_array($name, $args);
}
public function __construct()
{
// Call undefined method
$this->addOn('My Input');
}
}
index.php
<?php
include 'functions.php';
include 'MyClass.php';
$cls = new MyClass();
Here it is, but with some limitations though...
<?php
class SomeClass
{
private $_funcs = array();
public function setFunc($name,$func)
{
$this->_funcs[$name] = $func;
}
public function __call($name, $param)
{
if(!function_exists($name))
{
if(isset($this->_funcs[$name]))
$this->_funcs[$name]();
else echo "NO $name <br />";
}
}
public function dummy()
{
echo 'DUMMY<br />';
}
}
Then let's test this:
$sc = new SomeClass();
$sc->haha();
$sc->dummy();
$sc->setFunc('foo',function(){echo 'Hello New World!';});
// blah blah blah...
// blah blah blah...
// blah blah blah...
// blah blah blah...
// blah blah blah...
$sc->foo();
One of the limitation that I thought of is how to determine if you want to return a result from $sc level or not.
The result should be, based from the code above:
NO haha
DUMMY
Hello New World!
NOTE: I know this is not the best practice, OP, you should know it too. I just answered OP's question.
EDIT: To be able to determine if the function should return something, try taking advantage of the function name like r_sum with a prefix of r_ to determine that it needs to return something.
Example:
public function __call($name, $param)
{
if(!function_exists($name))
{
if(isset($this->_funcs[$name]))
{
if(strpos($name, 'r_')===0)
return $this->_funcs[$name](); // execute and return
else
$this->_funcs[$name](); // just execute
}
else echo "NO $name <br />";
}
}
But now, the other issue of this that I almost forgot, you cannot access the class properties via, new funcs.
SUGGESTION
Group your similar or related functions together into one static class so you can reuse your codes anytime anywhere.
//APP contains functions designed closely to work with your CMS
// example
APP::abort();
// HTML contains functions like getting page title, external reso, etc
// example
echo HTML::getTitle();
// ROUTE contains many routing reqs that you may need
// example
ROUTE::to('heaven');
// many more...
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Could this be classified as correct OOP programming?
class Greeting {
public $greet = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
function __construct($name) {
$this->name = $name;
shuffle($this->greet);
}
}
$hi = new Greeting('INSERTNAMEHERE'); /*NAME OF PERSON GOES HERE*/
echo $hi->greet[1] .' '. $hi->name;
For the sake of Keeping it Simple, I'd say it's okay. It's not too proper OOP though, nor is it particularly easy to understand code. Having working code is better than having no code at all though.
Let's go through your code:
1 class Greeting {
2
3 public $greet = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
4
5 function __construct($name) {
6 $this->name = $name;
7 shuffle($this->greet);
8 }
9 }
Line 1: says this class represents the concept of a Greeting. What is a Greeting? I'd say something like "Hello John" or "Hi John" or "Howdy John" is a greeting. And in fact, you seem to agree because in …
Line 3: … you do have a list of similar greetings, just without a name. But that property warrants the question why your class is named Greeting, when it really encapsulates multiple greetings already. Shouldn't the class be called Greetings (mind the plural) then?
Line 3: Naming the property "greet" wasn't a too good idea either. It's a property, so dont give it the name of a verb. Verbs are for methods.
Line 3: Although there is people who will tell you different, making the property public is rarely a good idea. Properties are about internal state and that state should not be accessible directly, but only through methods.
Line 5: Your constructor then tells me a Greeting has to have a name. If I wouldn't be looking at the source code already, I'd falsely assume this to be the name of the Greeting. But you really mean a Person's name. The argument should reflect that and be named something more indicative, like $greetedPersonsName.
Line 6: Assigning properties on the fly is a boo boo. If I look at the class definition, I want to see the properties immediately. Discovering them inside some method makes the code hard to understand. This will also not getting picked up when generating API docs. Avoid it.
Line 7: The shuffle is another unexpected thing. It's a non-obvious side-effect. If I was to instantiate a new Greeting, I'd expect the greetings to appear in the order they are listed. It's against the Principle of Least Astonishement to shuffle them in the ctor. The shuffling should happen from a public method that does nothing but shuffling, e.g.
public function shuffleGreetings()
{
shuffle($this->greetings);
}
Assuming the idea of the class was really to be a single Greeting that just initializes itself with one of the default possible values, we can also add a Getter like this:
public function getGreeting()
{
return $this->_greetings[0] . ' ' . $this->name;
}
This is better than doing
echo $hi->greet[1] .' '. $hi->name;
because it hides the implementation details. I don't need to know that the Greeting object has an array of possible greetings. I just want to get the Greeting combined with the set name. It's still far from perfect though, because you still would use it like
$hi = new Greeting('John'); // A Greeting named John? Why $hi then?
$hi->shuffleGreetings(); // Shuffling Greetings in a Greeting?
echo $hi->getGreeting(); // Why is it "Hello John" all of a sudden?
As you can see, the API is still pretty much full of WTF. A developer will still have to look at your source code to understand what's going on.
More on Side-Effects
While it may be tempting to put the shuffle into getGreeting you should not do so. A method should return the same thing for the same input. When I call getGreeting twice in a row, I can expect it to return the same result. You would expect 1+1 to return 2 always, so make sure your methods do too.
Likewise, if you want to have a single method to return a random item from the greetings property, dont shuffle the greetings array. If you would use the shuffle method instead, you would also change the greetings property. That ripples to any function reading from the property, e.g. when you do
public function getRandomGreeting()
{
$this->shuffleGreetings();
return $this->getGreeting();
}
a developer will experience something like this:
$hi = new Greeting('John');
$hi->shuffleGreetings();
echo $hi->getGreeting(); // for example "Hello John"
echo $hi->getRandomGreeting(); // for example "Hi John"
echo $hi->getGreeting(); // for example "Howdy John" <-- WTF!!
Use an implementation that doesnt change the property, e.g.
public function getRandomGreeting()
{
$randomKey = array_rand($this->greetings);
return $this->greetings[$randomKey] . ' ' . $this->name;
}
That is free of side-effects:
$hi = new Greeting('John');
$hi->shuffleGreetings();
echo $hi->getGreeting(); // for example "Hello John"
echo $hi->getRandomGreeting(); // for example "Hi John"
echo $hi->getGreeting(); // still "Hello John". Expected!
The API is still far from pretty though. If I think about the properties of a Greeting, I just dont think "Person's name". Just saying "Hi" oder "Hello" is still a valid greeting. It doesn't require a name. How about
public function greetPerson($personName)
{
return $this->getGreeting() . ' ' . $personName;
}
and then we can do
$hi = new Greeting;
$hi->shuffleGreetings();
echo $hi->greetPerson('John');
And to finally hide that our Greeting contains an array that needs to be shuffled, let's move our shuffleGreetings method back to the ctor and rename the class to RandomGreeting.
class RandomGreeting …
public function __construct()
{
$this->shuffleGreetings();
}
This might seem counterintuitive at first, because I told you not to shuffle in the ctor. But with the class renamed to RandomGreeting, it is much more to be expected that there is something happening behind the scenes. We just don't need to know what exactly. To reflect that, we should also make the shuffleGreetings method protected now. We just hide it from the public interface completely. Now our code reads like this:
$hi = new RandomGreeting;
echo $hi->greetPerson('John'); // ex "Howdy John"
This doesn't give you any WTFs because your code clearly communicates you'll get a random greeting. The classname clearly communicates what it does.
This is a little bet better now and we could end here, but one could still argue that a Greeting should not be able to greet on it's own, but is rather something that is done by a Person instead.
Improving it
Our findings should lead us to the conclusion that a Greeting should rather be a dumb Type encapsulating the Greeting message and nothing else. All it should do is return that message. Since the Greeting doesn't have any real behavior next to storing the message string, the easiest would be to create a Value Object, e.g. an object that is equal to another object by value of a property:
class Greeting
{
protected $value;
public function __construct($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
}
The other way to do it would be to make the various available greetings into separate types. There is very little gain to do that when your objects don't have behavior. You only need that if you want to take advantage of Polymorphism. However, having concrete subtypes does draw a few additional things to consider later on, so let's just assume we need it.
The proper way to do that in OOP would be to define an interface
interface Greeting
{
public function getGreeting();
}
that defines a class that wants to behave like a Greeting has to have a getGreeting method. Since interfaces dont implement any logic, we also add an abstract type that contains the greeting property and the logic to return it:
abstract class GreetingType implements Greeting
{
protected $greeting;
public function getGreeting()
{
return $this->greeting;
}
}
When there is an abstract class, there also needs to be concrete classes derived from the abstract class. So let's use Inheritance to define our concrete Greeting types:
class HiGreeting extends GreetingType
{
protected $greeting = 'Hi';
}
class HelloGreeting extends GreetingType
{
protected $greeting = 'Hello';
}
class HowdyGreeting extends GreetingType
{
protected $greeting = 'Howdy';
}
It's not absolutely necessary to have an Interface and an Abstract implementing the interface. We could have made our concrete Greetings not extend from the GreetingType. But if we had just reimplemented the getGreeting method on all the various Greeting classes, we would be duplicating code and were much more prone to introducing errors and should we ever need to change something, we'd have to touch all these classes. With the GreetingType it's all centralized.
The other way round is true as well. You dont necessarily need an interface. We could have used just the abstract type. But then we would be limited to the GreetingType whereas with an interface, we could potentially add new Types with much more ease. I admit I can't think of any right now, so it is probably YAGNI. But it's so little to add that we can just as well keep it now.
We will also add a Null Object that returns an empty string. More on that later.
class NullGreeting extends GreetingType
{
protected $greeting = '';
}
Object creation
Because I do not want to litter new classname all over my consuming classes and introduce coupling, I will a use simple Factory instead to capsule object creation:
class GreetingFactory
{
public function createGreeting($typeName = NULL)
{
switch(strtolower($typeName)) {
case 'hi': return new HiGreeting;
case 'howdy': return new HowdyGreeting;
case 'hello': return new HelloGreeting;
default: return new NullGreeting;
}
}
}
The Factory is one of the few pieces of code where you actually can use a swich/case without having to check if you can Replace Conditional with Polymorphism.
Responsibility
With object creation out of the way, we can finally start to add our Greetings class:
class Greetings
{
protected $greetings;
protected $nullGreeting;
public function __construct(NullGreeting $nullGreeting)
{
$this->greetings = new ArrayObject;
$this->nullGreeting = $nullGreeting;
}
public function addGreeting(Greeting $greetingToAdd)
{
$this->greetings->append($greetingToAdd);
}
public function getRandomGreeting()
{
if ($this->hasGreetings()) {
return $this->_getRandomGreeting();
} else {
return $this->nullGreeting;
}
}
public function hasGreetings()
{
return count($this->greetings);
}
protected function _getRandomGreeting()
{
return $this->greetings->offsetGet(
rand(0, $this->greetings->count() - 1)
);
}
}
As you can see, Greetings is really just a wrapper for an ArrayObject. It makes sure that we cannot add anything else but objects implementing the Greeting interface to the collection. And it also allows us to pick a random Greeting from the collection. It also makes sure that you always get a Greeting from the call to getRandomGreeting by returning the NullGreeting. This is awesome, because without that you would have to do
$greeting = $greetings->getRandomGreeting();
if(NULL !== $greeting) {
echo $greeting->getMessage();
}
in order to avoid a "Fatal Error: Trying to call method on non-object" when the getRandomGreeting method did not return a Greeting object (when there is no Greeting in the Greetings class yet).
The class has no other responsibility than that. If you are unsure if your class is doing too much or has methods that should better be on some other object, look at the methods in that class. Do they work with a property of that class? If not, you should probably move that method.
Getting it done
Now to finally put all that code to use, we add our Person class now. Since we want to make sure we can call a getName method on it, we create an interface before doing so
interface Named
{
public function getName();
}
We could have named that interface IPerson or whatever but it only has one method getName and the most fitting name is Named then, because any class implementing that interface is a named thing, including, but not limited to our Person class:
class Person implements Named
{
protected $name;
protected $greeting;
public function __construct($name, Greeting $greeting)
{
$this->name = $name;
$this->greeting = $greeting;
}
public function getName()
{
return $this->name;
}
public function greet(Named $greetable)
{
return trim(sprintf(
'%s %s',
$this->greeting->getGreeting(),
$greetable->getName()
));
}
}
Our Person has a required name and we demand it to have a Greeting as well. All it can do besides returning it's name is greet another Named thing, likely another person. And that's it.
To put that all together now:
$greetings->addGreeting($greetingsFactory->createGreeting('Hi'));
$greetings->addGreeting($greetingsFactory->createGreeting('Howdy'));
$greetings->addGreeting($greetingsFactory->createGreeting('Hello'));
$john = new Person('John Doe', $greetings->getRandomGreeting());
$jane = new Person('Jane Doe', $greetings->getRandomGreeting());
echo $john->greet($jane),
PHP_EOL,
$jane->greet($john);
Live Demo on Codepad
Granted that's quite a lot of code for a very simple thing to do. Some will call it overengineered. But you asked for correct OOP and while I am sure there is still room for improvement, it's quite proper and SOLID in my book. And it's easy to maintain now, because the responsibilities are closer to where they should be.
Hmm, two things:
shuffling that array and accessing it from the outside, and having the outside call rely on the array being shuffled, doesn't feel right. It would be nicer to have a method that returns the result of an array shuffling, and maybe also the name straight away.
It would be good style to declare all object properties beforehand so it can be documented later. So if you use $this->name, you should declare it.
Both points implemented could look like this:
class greeting
{
protected $greet = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
protected $name = null;
public function __construct($name)
{
$this->name = $name;
}
public function greet()
{
shuffle($this->greet);
return $this->greet[1]." ".$this->name;
}
}
from a beginners point of view it would be yes, but as this is a single object it cannot be orientated like you could with several objects.
True OOP is when you separate the individual entities of your application into objects / dependencies.
for example, a simple website would include the following:
Database
Error Handling
Sessions
Security
these are called entities and should not interact directly with each other, that's why there separate.
so if we wanted to interact Sessions and Security to make shore that the session is safe, we would add a method to the session object to return a PHP standard result such as array or string, this way many objects can interact with each other without relying on the actual object too much.
Looking at your attempt at a greeting class I would look at something like so:
class User
{
protected $data;
public function __construct(array $user_data)
{
$this->data = $user_data;
}
public function getUsername()
{
return $this->data['username'];
}
}
class Greeting
{
private $message = "welcome to mysite %s";
public function __construct(string $to_greet)
{
$this->message = sprintf($this->message,$to_greet);
}
public function getGreeting()
{
return $this->message;
}
}
the following would be used like so:
$User = new User(array(
'id' => 22,
'username' => 'Robert Pitt'
));
$Greeting = new Greeting($User->getUsername());
echo $Greeting->getGreeting();
now i have mentioned that objects do interact directly with each other but if they do that they should be encapsulated so that all the database objects such as Database,Result,DB_Error would only interact with each other.
this allows for code to be transportable to other projects without having to much of an issue, also known as libraries.
if the objects are closley related ina way that there all bundled together you could do something like this:
$User = new User(/*..From DB ..*/);
$Greeting = new Greeting($User);
echo $Greeting->getGreeting();
It would probably be better to have a greet method. The idea is that the user doesn't need to know that $this->greet is an array.
So:
class Greeting {
protected $greet = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
protected $name='You';
function __construct($name) {
$this->name = $name;
}
function greet(){
shuffle($this->greet);
echo "{$this->greet[0]} {$this->name}!";
}
}
$hi = new Greeting('INSERTNAMEHERE');/*NAME OF PERSON GOES HERE*/
$hi->greet();
I have to disagree with [Edit: Some of] the other answers you've gotten. Making greet private and adding a getter does little to increase encapsulation.
Regardless of that, however, I think it's pretty poor OO design. An object should represent some thing (dare I say, some actual obect?) IMO, the "objects" here would really be the people (or whatever), one of whom is greeting the other. The greeting itself should be a message passed from one of those objects to the other. We might write a "greeting" class to hold the text of the greeting, but even if we do the greeting object itself should be independent of the source or target of the greeting.
It's a bit off the mark, actually. First of all, public variables are generally bad. You shouldn't be accessing class's variables directly from the code. You should try to encapsulate functionality provided by the class into the class itself.
First, let me show you how a good kind of OOP code could look like based on your example:
<?php
class greeting
{
private static $greets = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
private $name;
function __construct ($name)
{
$this->name = $name;
}
function doGreeting ()
{
$i = array_rand(self::$greets);
return self::$greets[$i] . ' ' . $this->name;
}
}
$hi = new greeting('INSERTNAMEHERE');/*NAME OF PERSON GOES HERE*/
echo $hi->doGreeting();
Now, let's talk about the differences here.
First, the greets are stored in a static variable. Since these texts probably do not vary instance by instance, it's simply more efficient to store them in a static variable that is shared by the entire class, so every instance do not have their own copy of the array. You will also notice that it's private. This is encapsulation. The code outside does not need to know about the inner workings of the class, like the variable names. Outside code does not need to know about the array, since it should only be used within the class itself.
Another minor detail, is that the name is also declared there as private, since all class variables should be private in general for encapsulation. If they need to be accessed, that should be done via setter and getter functions, which can provide additional validation for values, if needed.
The code flow is also a bit different. Instead of using the class variables directly from the outside code, we get the class itself to produce the greeting and return it as a string. This way, the outside code does not need to know how the greeting texts are produced or where the name is stored. It jsut needs to know the API, i.e. the functions, their parameters and return values. How they actually work should be left for the class itself.
Additionally, since this is obviously functionality that is intended for the greeting class, it makes the code more reusable as the functionality is coded into the class. Part of the point of OOP is to create good reusable code that can be used where it is needed. When the class functionality is in the class itself, the same code does not needed to be coded elsewhere.
Remember encapsulation and reusability. These are two important points of OOP.
One of the basic ideas behind OOP is that you have objects that have responsibility over certain data structures in your code. what you have written above is really just a data structure, not really a full on object, it holds the data for the greeting, but doesn't really have responsibility over handling it and providing it for other objects.
A "better" object would look something like this:
class greeting {
protected $greet = array('Hi','Hello', 'Howzit', 'Ola', 'Whats up');
protected $name;
function __construct($name) {
$this->name = $name;
}
public function greet() {
return $this->greet[rand(0,5)] . ' ' . $this->name;
}
}
$hi = new greeting('INSERTNAMEHERE');/*NAME OF PERSON GOES HERE*/
echo $hi->greet();
Now your greet object is in total control of the greeting and your application code doesn't have to care about how that object is set up, it just has to care about the few functions it can use to get the greeting. If you wanted to eventually internationalize or change the greeting in some way, all you'd need to do is change that one object to do it.
Also, just to note, using objects does not make your code OOP. It needs to be object oriented, which means using objects to define discrete tasks that your application will need to perform and not making every other piece of the application have total access to all of it's data to do with what it will. Then, you're just building data structures.
its is not completely correct OOP because the $greet variable is not encapsulated.
to make it 'more correct' (whatever that means), you would have to make the $greet param private and create some get and set methods for it (same goes for the $name variable -- which also should be declared before it is used).
in php a get method is like so:
if i want to get the var:
$hi = new greeting('INSERTNAMEHERE');/*NAME OF PERSON GOES HERE*/
echo $hi->__get('greet') .' '. $hi->__get('name');
the get is created inside the greeting class:
function __get($var){
return $this->$var;
}
and set is the same:
function __set($var, $val){
$this->$var = $val;
}
I would probably use getters/setters for $greet, instead of making it public. I don't see why it wouldn't be considered OOP though.
http://en.wikipedia.org/wiki/Object-oriented_programming
I've been working in PHP5 for a couple of years now and have developed a lightweight MVC framework that I use to speed up site development. Works great, automated formbuilder, autoSQL module, etc.
One bad habit that I have developed, however, is relying on $this as an easy object param. I have yet to figure out how to truly encapsulate data without having to extend from a base class (where all site variables are defined) and using a setter method to populate each object instance with the passed $this object. Everything works, but it's ridiculous that each object has to know about the entire application state. I would like each object to perform it's designated task only requiring a minimum knowledge of the "outside" context.
For example, let's say I have a class that generates a customer's account details:
// pseudo account
Class account extends siteBase {
protected $formObj;
public $custID = 1;
public $name;
public $email;
// etc...
function __construct() {
$this->formObj = new FormBuild($this); // easy $this passing
$this->formObj->getFormData();
$this->formObj->build();
}
}
// pseudo form builder class
Class FormBuild extends siteBase {
protected $data;
function __construct($caller) {
$this->set($caller);
}
function set($arr) {
foreach($arr as $key => $val) {
$this->$key = $val;
}
}
function getFormData() {
$this->data = new FormQuery($this); // more easy $this passing
}
function build() {
foreach($this->data as $key => $val) {
echo $key . " " . $val . "<br>";
}
}
}
Class FormQuery extends siteBase {
function __construct($caller) {
$this->set($caller);
}
function query() {
$sql = "SELECT email, phone FROM account WHERE custID = '$this->custID'";
// query & return return result, etc.
}
}
What do the "pros" do this in situation? I'd love to clean up the interface a bit...
There are many approaches to this problem. Here are a few
Global or class constants
External config/static data (INI style, xml, yaml, database, etc) read by a config class of some sort
The registry pattern
The depdency injection/inversion-of-control pattern
They all have their ups and downs - there is no "one true solution."
Try to take the perspective of the client code: a derived class should have the same interface as the parent class but a different implementation.
A messy interface such as methods in parent classes that aren't used in derived classes should never exist and would be a good hint to start refactor. Another strong hint that you most probably noticed is that the methods don't take the same arguments (comparing account::__construct() to FormBuild::__construct($caller), both deriving from siteBase::__construct()).
I would refactor with configuration in mind, what if siteBase includes a database but a deriving class needs a different/a set of different databases? Try to draw out your common classes and see which ones that really share signature, pair together a few at a time.
Both responses above are correct.
I have built-in a registry object/properties container that I pass to appropriate objects that no longer need to inherit from an application base class. Bit of a hassle compared to passing $this around, but makes for better planning and forces me to define what my objects need to know vs. knowing everything.
The refactoring advice also got me stripping down a few frequently used objects to only doing their job vs. several jobs at once.
Still a ways to go though, I've gotten used to knowing everything about the application from almost anywhere in the app...