F
F
Fedor Ananin2017-01-21 08:50:35
PHP
Fedor Ananin, 2017-01-21 08:50:35

Question about OOP, how to use?

Ladies and gentlemen, I have a problem.
I started learning PHP in the distant bearded years, in other words, php 5 was just appearing. I studied literature, which was written mostly for php 3 and 4. And now I'm faced with an interesting problem.
My skill allows me to write almost anything I want. I can write neat code, I can design complex web applications. But I don’t stick into OOP at all ...
Here, for example, you need to make a simple photo gallery. There is a stupid list of galleries without nesting, each gallery has an unlimited number of photos with descriptions. How to write down all this in OOP? If I take the gallery for an object, what should I do with the photos? For each photo do $image=new image($id_photos); ??? Or use a variant like $gallery->getPhoto($id_photos); ?
I've been really into static classes lately. They are global, they are very similar to regular procedural programming, but they provide a greater level of isolation.
95% of the code I write for personal needs. Rather, no one but me works with this code. There is a simple CMS for client sites, there are a couple of web services that are supported only by me.
I feel out of the crowd because I don't use OOP. But I don’t use it ... because I don’t fully understand how and why. If I write a blog, do I need to take the entire blog as an object, and pull out the posts using the $blog->getPost() or $post->content() principle? What to do with comments? In fact, each comment is a separate object. Am I making life difficult?
Call me a shitcoder, but

$post=BLOG::getPost($айди_поста);
echo $post['content'];
$comments=BLOG::getComments($айди_поста);
echo $comments;

it works. And I totally understand how. The example is very simplified, but I think you get the point.
UPD:
As I understand it, if I am involved in the development of very sophisticated projects where more than two programmers work, then without OOP there is nowhere at all. If I am writing something simple, if something is rarely changed, or if something is complex, but alone, then it is worth writing in a way that is convenient, and not in the “right way”. After all, the most important thing is the result, and not the way to achieve it (provided that my code works without errors and does not load the system to dullness)

Answer the question

In order to leave comments, you need to log in

7 answer(s)
T
ThunderCat, 2017-01-21
@sarathorn

Here, for example, you need to make a simple photo gallery.
Using your example, so that it would be clear on the fingers, I apologize in advance to those present for primitivism. In this case, you will have a collection of objects, which is also an object, it's like arrays, if you primitize concepts to the limit, some can be nested in others. Let's do it like this:
$image= new Image(); //создаем пустой объект имаж, чтобы иметь его настройки(таблица, поля...)
$gallery = new Collection ($image); //создаем новую коллекцию объектов типа имаж, пока пустую.
$gallery->getCollectionByField(array("galleryid"=>"64")); // инициализируем из базы, используя
// ид галереи, теперь в гэлери одной строчкой мы загрузили все картинки в свойство (например),
// $gallery->collection  и можем к ним обращаться как к элементам массива, и в свойстве
// $gallery->collection[1] будет объект типа $image. Как вариант реализации.

A lot of code remains in the object, for you it is a "black box", only inputs and outputs are visible, everything inside is hidden, but works as it should, because broken into methods and debugged piece by piece.
As for statics - as they say in any normal source - statics should be avoided to the maximum, there are several reasons for this:
- statics loads the RAM, i.e. static objects are always created, regardless of the need to use them
- statics are difficult to test, not always, but often, because the global scope brings problems of crossing the areas of responsibility of methods, often this violates SOLID , especially if you poke statics everywhere. Read, see how normal code in objects should look like - you'll like it.
ps:
your code - why not write like this:
$post=BLOG::getPost($айди_поста);
// меняем 
$post = new Post($айди_поста);

echo $post['content'];
// меняем 
echo $post->content; // не обязательно так, может вот так:
echo $post->getContent(); // тогда при выводе можно будет сделать какую-то предварительную обработку, 
//заменить тэги, еще что-то...

$comments=BLOG::getComments($айди_поста);
// меняем
$comments = new Comments($post);
echo $comments->getTree(); // хотя тут скорее всего от вьюшки зависит, я бы тут возвращал не 
// строку, а массив для итератора, это правильнее для разделения на мвц, мухи отдельно - 
// котлеты отдельно, в смысле код и хтмл.

S
Saboteur, 2017-01-21
@saboteur_kiev

Procedural programming approach - functions and algorithms are at the head.
Data is at the head of OOP.
You have data, a simple int or a complex structure in the form of an account (username, password, email, full name, etc)
You pack this data into a class, add methods to it that work with this data.
This allows you to operate on data as a class. You know for sure that the data, in the format in which it is located and processed inside the class, is not used ANYWHERE, except in this class.
If another class needs data from your class, a method is created for this.
This allows you to change the class however you want while keeping the methods. We need something in a new form - we create another method. Those who used the old - continue, those who updated - use the new.
This allows you to encapsulate all classes really well in complex projects, keeping the size of the class such that it can fit into the head of one programmer, and, if necessary, be corrected, modified, rewritten.
This is basically the essence of OOP.
Everything that follows - inheritance, polymorphism, and so on - is an attempt to make OOP more flexible, because there are situations ...

B
bioroot, 2017-01-26
@bioroot

I'll add my five cents. At one time, the idea of ​​​​interfaces helped me a lot, although they took root quite moderately in php and mostly at a low level. In your example, you could move comments processing into a separate method that would require the argument object to implement an interface that requires a getComments method. Further, this method itself builds a tree according to the comments. Then you pack this method into a file and when you need a comment tree for any entity (not just a blog, but a photo gallery, news, etc.) you pull this magic method. As long as you follow some of your own comment format conventions, it will work by itself. And if you slip an entity that does not have a getComments method, you will immediately know about it.
A specific example is of course sucked out of thin air, but in systems with more than three entities, interfaces help a lot. You can even at the design stage lay down the requirements for incoming data for the implementation of each specific piece of logic. And the bonus is that this piece of logic will continue to work correctly with any data that meets the requirements.

C
Cavin March, 2017-01-21
@ForbsmC

Well. I myself am only studying OOP, but I liked OOP in puff more than procedural. The code looks much smaller and more concise.

A
alexchin, 2017-01-21
@alexchin

Development best practices show that using frameworks like GodeIgniter , YII , Laravel , etc. ( so as not to offend anyone ) are justified and frameworks take on most of the routine work - security, routing, caching, ORM , etc. However, frameworks are developed in an ideal object world where OOP is used to its fullest. Where is the place for your objects in this world? Concentrate on your subject area! If this is a block with posts and comments, then create an object model as shown above. The framework, by the way, can help, for example, to implement the materialization of objects from the storage system or a convenient basis for the class hierarchy. In complex projects, DDD is also quite applicable . Also, the development of OOP ideas is facilitated by clean code. .

N
Neznayka xD, 2017-01-22
@Neznayka1979

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question