Page 1 of 1

Use static class here?

Posted: Fri Feb 08, 2013 8:16 pm
by pinehead
I'm writing a class that allows me to send an email randomly throughout my app. basically administrator notifications to myself. I don't want to have to instantiate the class every time I want to do this so i'm using a static class.

Question 1) Is this a good use of a static class?

Question 2) Thoughts on my class?

Question 3) Any thoughts on why i run this code i get the error " classes that i write Fatal error: Call to undefined method Notify::sendNotification() in classes/testclass.php on line 5"

Code: Select all

class Notify  {

	private $email = "email@awesomesauce.com";
	private $phone = "";
	private $sms;
	private $subject;
	private $message;
	
	
	public static function sendNotifiction($subject, $message, $sms) {
		self::$subject = $subject;
		self::$message = $message;
		self::$sms = $sms;
		
		
	}
	
	private function sendEmail() {
		mail(self::$email, self::$subject, self::$message);
		if (self::$sms) {
			mail(self::$phone, self::$subject, self::$message);	
		}
	}
	
}
testclass.php

Code: Select all

Notify::sendNotification("testing subject","testing message", true);

Re: Use static class here?

Posted: Fri Feb 08, 2013 9:49 pm
by Christopher
pinehead wrote:Question 3) Any thoughts on why i run this code i get the error " classes that i write Fatal error: Call to undefined method Notify::sendNotification() in classes/testclass.php on line 5"
The method in the class is call sendNotifiction() which should be sendNotificAtion(). It us correct in the test script.

Re: Use static class here?

Posted: Fri Feb 08, 2013 10:46 pm
by pinehead
Yup your correct it's all working great now.
Thanks,

Re: Use static class here?

Posted: Tue Feb 12, 2013 5:48 pm
by pickle
As far as I'm concerned, this is a perfect use of a static class. You don't need to maintain object state between invocations, and there's no "loading" really that needs to be done, so a static class is just what you need.

The only comments I would make is are
  • sendEmail() never gets called
  • Does sendNotification() need to exist? The way you've described how you're using this function, why not just call sendEmail() directly, passing the necessary parameters, and of course declaring it public & static.
  • If you do follow the point above, $sms, $subject, and $message can go away - they don't really need to exist for any reason other than passing information between sendNotification() and sendEmail()
  • Totally personal preference, but I would rename the class to Email and the called function send(), so the code looks like Email::send()