Need advice with design - changing static into normal methods - php

My whole project is basically divided into two parts:
core
helper classes
User creates his custom classes and uses methods from helper classes in there like:
\Project\System\Helpers\Class::foo();
So every public method in each helper class is declared as static. I've came up with an idea to change this, make all user custom classes inherit one special class:
class SingleBeingInheritedClass {
public function helper($class)
{
return new \Project\System\Helpers\$class; // it's just to show the idea
}
}
so that instead of calling static function, user could write:
$this->helper('class')->foo();
The problem is I use some of these helper classes inside a couple of core classes. And I don't want core classes to inherit anything related to helpers.
In these core classes I also don't want to make the code longer and initialize objects in every method using these helpers.
How should I handle this? Or maybe static methods aren't that bad here?

You wrote:
I also don't want to make the code longer and initialize objects in
every method using these helpers.
I you would like to avoid instantiating objects, then you shall stick to static methods. In my projects I use static methods for helpers, for the exact same reason.
These helper classes are then used as 'function libraries'. In this case, class is more like a namespace for the helper functions, not something which gets instantiated.

Related

make a static method for all classes in PHP using meta class Class?

How can I add a static method for all classes of my php using an class Class or class Object (meta class) like
class Object //meta class, all classes php henerit of it
{
static function test() { return 42; }
}
now if I make a new class like :
class User
{
}
I want to be abble to write :
User::test();
same with all classes I will write
PHP has no concept of metaclasses; the way in which classes themselves behave is essentially hard-coded into the language. (You could argue that internal classes written in C conceptually use a different metaclass than userland classes written in PHP, since they can implement a different set of hooks; but that's not a distinction that's visible in the language, and not really relevant to your example.)
It also has no universal base class; there is no "Object" or "Any" or "Mu" class which all other classes implicitly or explicitly inherit from.
More importantly, there is no way to add to an existing class; there is no way to "re-open" or "monkey-patch" a class, or add methods via "extension classes". So even if there was a default metaclass or universal base class, you wouldn't be able to change it. Any classes you wanted extra behaviour on would have to opt-in to being instances of a non-default metaclass, or inherit from a non-default base class.
It's not clear exactly what the use case is, but there are a number of things you can do:
Write your own base class which a large number of classes inherit from, to put your "universal" methods in.
Use traits which enable "horizontal code re-use", essentially by "compiler-assisted copy-and-paste".
You have to use the trait in each class where you want to "paste" its contents, but they will then be inherited from there, so you can have a handful of unrelated "base classes" all sharing a set of methods "pasted" from the same trait.
On the other hand, you might want to create a sub-class which takes an existing class and adds some methods using a trait.
More complex cases would require you to patch the source code of classes themselves. For instance, using a custom autoloader and https://github.com/nikic/php-parser to parse and manipulate class definitions before they are compiled. For instance, this just-for-fun sweary library installs as a Composer plugin and loads classes via a stream wrapper which removes restrictions such as "final".
Why not use a trait?
Unfortunately I haven't heard of anything like what you need in PHP.
<?php
trait Obj
{
static function test() { return 42; }
}
class User
{
use Obj;
}
echo User::test(); //prints 42
Hope this helps.

Disable old-style constructors (PHP4-)

I am working on an MVC framework in PHP.
I have several controller classes called "index" with methods called "index" within them. The classes do not have __construct() methods.
Inevitably, this is resulting in PHP calling the "index" method as the constructor instead, using the old PHP4 convention of the constructor being the method with the same name as the class.
Is there any way to disable this behaviour or do I have to define an empty __construct() to prevent it? (Or just change my own coding style so I don't have methods with the same name as their classes.)
I want PHP5 to stop parsing for the PHP4 constructors essentially.
Ilmiont
I have been down the same road with MVC frameworks before and I have never heard of an index() function being called like this. Upon instanciation it will call the __constructor if present or do nothing. When calling your controller you should be geting the class and method name and checking if they exist and if they do then instantiate it. However if you have the same general setup as me you should have a registry storing all of your variables being passed to the controller when you create an instance, then when/if the view is called from index it should pass the altered registry to the view

cakephp components and helpers breaks oop logic! How should I proceed?

I have a string manipulation class that I need in views and in controllers also!
I saw that cake reuses code in Components and in Helpers for this type of situations which on my opinion breaks the OOP logic (eg. Session->read)!
Instead of doing this I created a vendor class which I imported in a StringsHelper and in a StringsComponent. I then created an identical function which instanciates the Vendor/String class and returns the results from the corresponding function. This is not quite inheritance and still redundant, but if I change code in my class it changes everywhere.
Is there a better way to do this?
You do not need to wrap this kind of class in a Helper or a Component.
You could simply create a class with static methods and put it in APP/Lib like mentioned by Mark.
<?php
class StringTool{
public static function manipulate($string){
...
}
}
and then use it in whatever class you need, wether in a Component, a Helper, a Model, etc.
<?php
$s2 = StringTool::manipulate($s1);
I asked this same question before. Best place is in app/Libs, where you can put a class with static helper functions that can be used anywhere in your application, including controllers and views.
Import the class using App::import('Lib', 'YourClass')
CakePHP - Where is the best place to put custom utility classes in my app structure?

Prevent/Restrict Method Inheritance

I have an application in which a number of objects are all extending an abstract class which defines methods like create() edit() retrieve() and delete(). Since each of the child classes use the same logic for these functions, the abstract class defines that default behaviour, and in the few cases where it needs to be augmented, the child classes can override or use the hooks I've built in.
Now I'm having the situation where some of the child classes need to be made immutable, meaning that they shouldn't have edit() or delete() methods. This need sounds to me like a job for an interface named something like immutable which the immutable classes could implement. Problem is that interfaces don't stop methods from being called, they just enforce a method's existence. So this is obviously not going to work.
Making two parent classes, one for mutable objects and one for immutable ones is ugly and is probably asking for problems down the line which maintenance. I could have the immutable objects override the offending methods with an empty method that did nothing, but that also seems messy and like I'm not doing proper OOP at that point.
So what would you suggest as the best way to allow a large set of classes to all inherit a set of methods, but for some of them to not inherit all of the methods? (The application in question is written php, but general OOP techniques from any language can still be helpful).
create an immutable-base class as a child of the base class.
the immutable-base should implement final overrides of edit() and delete() which do nothing or throw an error.
Final, so that all immutable children are guaranteed not to be able to edit or delete
bonuses of this strategy
easily check if an object is immutable by testing for instanceof immutable-base
easily change objects from immutable and back again by modifing what it extends
Actually creating classes that have empty methods or throw errors is bad - such methods are confusing, they take up space and do nothing.
A better approach would be to make the immutable class the base class and make the mutable class extend it with adding methods for modification. This way each class has only those methods, that really belong there.
I like Java's approach to this. Throw an exception. Create an UnsupportedOperationException and for those implementations that shouldn't use a specific method throw one to let the user know they can't use this functionality for this implementation.
Another thought I wanted to throw out as a possible solution. Classes could implement an interface that looks like the following:
Interface Immutable {
const immutable = true;
}
and then the Base abstract class can write the delete() and edit() methods with
if (!$this->immutable) {
//do_stuff
}
This would also extend well to other classifications of class, like NonDeletable and NonEditable to allow for more fine grained behaviour.
Here is super short workaround, make your method final and start it with:
if(self::class!=static::class) return;#or throw an error
It will not prevent inheritance itself, but methods will not work in children classes (with error or without - is up to you).
As of PHP 5.4, you can use Traits.
For example, you could make a base class that only includes the methods that all child classes have:
class EntityManager {
public function create() {/*...*/}
public function retrieve() {/*...*/}
}
Then you could define a couple of traits:
trait EditTrait {
public function edit() {/*...*/}
}
trait DeleteTrait {
public function delete() {/*...*/}
}
You would then create an immutable child class like this:
class LogManager extends EntityManager {
...
}
And a mutable child class like this:
class ContactManager extends EntityManager {
use EditTrait;
use DeleteTrait;
...
}
Traits have some advantages over some of the other solutions here such as:
No duplication of code.
Single base class.
Methods that don't work or don't make sense, don't appear on classes that don't support them (especially important for docs and apis).

How to access libraries inside a controller?

I'm building a small framework that I can use for repeated mundane stuff on future small projects.
I'm stuck on the best way to access libraries from inside a controller. I originally implemented a system similar to CodeIgniter's whereby my main controller class is basically a super object and loads all the classes into class variables which are then accessed by extending the controller and doing like $this->class->method()
I find that a little ugly, though. So I thought of just loading each class individually on a per-use basis in each controller method.
What's the best (cleanest) way of doing this?
To only ever have one instance of each class, you could create a simple service container.
class ServiceContainer
{
protected $services;
public function get($className)
{
if (!array_key_exists($className, $this->services)) {
$this->services[$className] = new $className;
}
return $this->services[$className]
}
}
Then create one ServiceContainer instance per application. Inject the container into all of your controllers and use
public function someAction()
{
$this->container->get('Mailer')->send($email_data);
}
Simple example, and obviously needs a lot of work to make useable (for instance autoloading needed and handling of file paths for ease of use, or easier way to add services without getting them, etc).
I dont like the way CodeIgniter does it. Its never seemed right to me. I favor an auto loading class pushed onto the spl_autoload stack. And then just calling the class as normal like:
$class = new SomeClass();
PHP provides autoload functionality with SPL and spl_autoload (and related functions). You can register a custom autoloader for your library code.
For the shared functionality handled by your application, have you considered the Front Controller design pattern?

Categories