Getter & Setter also for in class usage? [closed] - php

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 8 years ago.
Improve this question
It is a bad way of programming, when i get access to my private/protected class members directly in the class via my getter/setter methods?
Alternative #1
<?php
class A {
private $myVariable;
public function getMyVariable() {
return $this->myVariable;
}
public function doSomething() {
$variable = $this->getMyVariable();
}
}
?>
Alternative #2
<?php
class A {
private $myVariable;
public function doSomething() {
$variable = $this->myVariable;
}
}
?>
Which way do you prefer? I think the first solution is more readable in constrast to the second one. Please let me hear your opinions.
Thanks in advance.

Since you are determined this is not a duplicate, I will copy the points from this response relevant to this case:
Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.
Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).
Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.

Maybe you should think in another way: Why do we need getter/setter? They abstract direct access to a field. Even if the Getter does nothing other than setting a value, it can protect you later on. Changing a field to a Getter later is a breaking change, especially in PHP IDEs (badumm). So I think whenever you want to protect a field to prevent vulnerable/buggy code, use getter/setter.

Related

Return type hints in Laravel. Good or bad idea? [closed]

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 2 years ago.
Improve this question
I analyzed my Laravel project using phpstan (https://github.com/phpstan/phpstan). One of the most frequent complaints are concerning methods without return typehints, which I think are valid complaints. So I thought I'd start adding typehints to my controller methods (ie public function index(): View ). Most of them returns either Illuminate\View\View or Illuminate\Http\RedirectResponse.
Questions:
Is this even a good idea? I think it generally makes things clearer, but return typehints aren't using anywhere in the Laravel documentation. Maybe it isn't good practice?
My big problem is some methods that return either or. Ie for example if the user is logged in they return a View, if not they return a RedirectResponse. How do I do return typehints for those methods?
I second #Alex Karshin comment.
Taylor Otwell stated his opinion clear in a proposal to type hint everything that could be type hinted.
I personally like to use type hints anywhere possible, like for defining properties or arguments for methods and functions or as return types. Spatie or BeyondCode for example uses them too.
Currently, PHP does not allow union type hints, but will be in PHP 8. Until it's release you can use DocBlocks for that matter:
/**
* #var string|int
*/
protected $property;

How should I keep my constants in PHP [closed]

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 6 years ago.
Improve this question
Right now I am having a big amount of constant strings and enums in my project. Since the beginning of it I was using the following approach (pseudo php example code):
class Constants implements iStatuses, iEmailTypes {
}
interface iStatuses {
const STATUS_NEW = 1;
cosnt STATUS_UPDATED =2;
...
}
interface iEmailTypes {
const EMAIL_TYPE_NEW = 1;
const EMAIL_TYPE_UPDATED =2;
...
}
This approach allowed me to get my constants in a following way anywhere in a code, since I included 'Constants' class in the index.php.
$this->sendEmailByType(CONSTANTS::EMAIL_TYPE_NEW);
However, I can totally see downsides of the approach:
Constants class is overloaded with a lots of enums and constants and it is very hard to get right constant. Naming convention helps to solve it, but I don't like this, since it requires additional thinking to identify what constant I need
Constants class is too big and messy
I need to keep tracking of all the interfaces, being implemented by Cosntants class.
Since my project is becoming much more bigger now, and we need to merge it with another project's code, it is required to have class Constants approach changed. However, I got too many dependencies based on that class. How should I re-struct that approach, in order not to break old code that used values of constants class.
Please, share your thoughts and suggestions, how to improve my 'constants' approach, or confirm that it is decently good and I should support it.
Thank you in advance.
Why not just having constant classes for each context. i.e.
class Statuses
{
const STATUS_NEW = 1;
const STATUS_UPDATED =2;
...
}
class EmailTypes
{
const EMAIL_TYPE_NEW = 1;
const EMAIL_TYPE_UPDATED =2;
...
}
Later on when you or other programmers want to contribute to your application they easily can check related constants on the subject they expecting, instead looking into a large pool of constant.
.e.g once looking for a flag around email types I would expect to find it within EmailType:: and if its not there, feel confident to add it in the same class.

Using method return value as argument vs setting class variable in one method and using it as an argument of another [closed]

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 8 years ago.
Improve this question
I was wondering what are the pros and cons of these 2 programming styles, is it just a matter of taste or is one the desired way?
using a method return value as an argument for another method :
public function add($data)
{
$this->uploadFilesToPreflight(
$this->addOrderFilesToDB(
$data['shop'],
$data['filesData']
)
);
}
VS setting a protected class variable in method 1 and using it as method 2 argument:
public function add($data)
{
//does some stuff and sets $orderFilesArray
$this->addOrderFilesToDB($data['shop'], $data['filesData']);
$this->uploadFilesToPreflight($this->orderFilesArray);
}
The question is, what is the class supposed to be? And does the class have a state?
If the class is supposed to be a service where add($data) can be called multiply times and the behavior should not change the first option would be better.
If the class has a state and it's behavior is supposed to change by call add($data) then the second option is fine but you have to be aware that this can cause side-effects if the class has other methods that rely on $this->orderFilesArray.
To provide a better answer on what option is best, you would have to post a broader context of the class.

Is there any downside with using the Ghost Lazy Loading pattern in this way? [closed]

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 8 years ago.
Improve this question
About the duplicate vote: This question is about the downsides of this approach, not about how to make this work; You can see it in this way: that question asks how to do something and the answer says something useful, however, I ask about the downsides of the answer.
TL;DR: will I encounter any technical difficulty by using this wrapper class later on? Why I haven't seen anything like this before?
I've been experimenting learning techniques for profiling recently and I found that creating the PDO instance is a place that could be optimized (~5ms). I don't need to use it in every call, however I'm creating it in every call from my code's structure. So, I just made this small class up:
<?php
namespace Library;
// Wrapper for \PDO. It only creates the rather expensive instance when needed.
// Use it exactly as you'd use the normal PDO object, except for the creation.
// In that case simply do "new \Library\PDO($args);" with the normal args
class PDO
{
// The actual instance of PDO
private $db;
public function __construct() {
$this->args = func_get_args();
}
public function __call($method, $args)
{
if (empty($this->db))
{
$Ref = new \ReflectionClass('\PDO');
$this->db = $Ref->newInstanceArgs($this->args);
}
return call_user_func_array(array($this->db, $method), $args);
}
}
To call it you only need to modify this line:
$DB = new \Library\PDO(/* normal arguments */);
And the type-hinting if you are using it to (\Library\PDO $DB).
It works flawlessly. It's also blazing fast (~0.2ms) when not using the PDO object and only introduces those ~0.2ms delay when using it (completely negligible). Now, I'm still learning about proper OOP, namespaces and general code structure, so I think I'm not qualified enough as to answer my own question yet:
Will I encounter any technical difficulty by using this wrapper class later on? Why I haven't seen anything like this before? therefore, why is this not more common or even default PDO behaviour?
Note: I intend to extend it furthermore by adding few more methods.
To answer your question: There is nothing wrong with this. This is a common optimization pattern, known as lazy loading, as you also mention in the comments.
While it could be implemented in different ways than what you have done here, your approach looks perfectly fine to me.

Rule of thumb on what to make object PHP [closed]

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 9 years ago.
Improve this question
When using Object-Oriented programming in PHP is there a simple rule of thumb on what should be made into an object or should you try to make the entire program using object-oriented code. I know this is quite opinion based but I can't seem to find any resources that could answer it for me.
Thanks.
I would suggest to read general oop concepts to get grip on that: http://oopsconcepts.blogspot.de/
What an object should be is largely language independent and whether your function should be an object or not fully depends on the context in what it is used.
Trivial code is usually not improved by making it object oriented.
In a scenario where your function is injected into something and must be replaceable it might make sense to make an object that implements an interface out of it.
Objects (or rather classes) should relate to a specific noun. For example, you might have a class called User, or Product. Functions generally are verbs. So you might have something like Product->Update().
Simple having a collection of unrelated functions in a generic Class does not constitute good OOP design. If the function is simply doing as you've advised, then it shouldn't have its own class.
A fairly standard pattern to follow with the kind of trivial, but global function your are discussing is to add it to a Utilty class.
In principle that is simply a class with public static member methods, that would normally be grouped by relation - exactly as you would a file of functions.
class MyFileUtility
{
public static function FileToArray($filePath) { // do stuff }
public static function ArrayToFile($array, $filePath { //do stuff }
...
}
$array = MyFileUtility::FileToArray('somefile');
Now you will use the methods of the Utility exactly as you would a function, but they are in a class, if it makes you feel better.
There are a couple of benefits:
Auto-loading will work, so long as you have configured it.
IMO You will generally be in a better / safer namespace situation.
If you like typing "::" You are well in :)
_____________ Edit _________________
Here is an explanation of a static Utility class added for clarity.
http://en.wikipedia.org/wiki/Utility_pattern

Categories