A
A
Anton R.2019-07-23 13:29:13
PHP
Anton R., 2019-07-23 13:29:13

Where can I get real code examples of using OOP in web services?

I read literature and online sources and EVERYWHERE examples are given "from life" of the type: there is a car, this is an abstract class, and there is a truck, a bus, etc., these are concrete objects ... And stuff like that, but these examples do not explain HOW to use the OOP approach for example, when writing a Blog or Bulletin Board engine or some other SPECIFIC web project.
I understand what OOP is with examples from life, but I still don’t understand how to use it, for example, when displaying a bulletin board, user registration and other functions. I ask you to help with specific examples to understand how to use it in real web projects, and not on the example of "cats and dogs" or "building airplanes".
Thank you in advance.

Answer the question

In order to leave comments, you need to log in

7 answer(s)
N
netcore, 2019-07-23
@netcore

There is a group of people who do not understand anything in programming, but they have an idea, an understanding of how the product works, and money (but this is secondary) Let's
call this group of people business
The product of this business is a news site. Let's take a news site as an example, because it's essentially the same blog.
There is a programmer who understands how to automate the actions of this idea and digitize the behavior of the product.
First, the business describes the pain that the product solves
. What is the pain? The business used to sell newspapers, and now it wants its own online newspaper.
1. They don't want to spend money on printing, but just make news posts and articles.
2. They do not want to pay money for transport costs to deliver newspapers, but to do mailing lists by e-mail
3. They want to receive feedback (comments)
this is enough for an example.
Ideally, a business orders a design. How it should look.
Ideally, there is also a contract manager who knows UML, but these are wet fantasies, so let's assume that there is a business and there is a programmer.
Then the entities of this product and the actors in this product are described.
What can we understand from this? What entities do we have?
1. post - news or article on the site.
1.1. At this stage, we find out from the business what is the difference between the news and the article.
Business says: news (for example) has only one picture, text.
The article also has text, but there can be several pictures, and there can be no comments.
Business forgot about the fact that there is also a date in the design, here the programmer himself thinks it out by looking at the layouts.
As a result, we get one abstract Post model and two implementing it: Article and News.

public abstract class Post
    {
        protected Post(string text, int writerId)
        {
            Text = text;
            CreationDate = DateTime.Now;
            WriterId = writerId;
        }

        public int Id { get; set; }
        public string Text { get; private set; }
        public DateTime CreationDate { get; private set; }
        //Идентификатор писателя статьи\новости
        public int WriterId { get; private set; }

        //Автоматически подтягиваемая из базы модель писателя через ORM по WriterId
        public virtual Writer Writer { get; set; }

    }

    public class Article : Post
    {
        public Picture[] Pictures { get; private set; }

        public Article(string text, int writerId, Picture[] pictures) : base(text, writerId)
        {
            Pictures = pictures;
        }
    }

    public class News : Post
    {
        public Picture Picture { get; }
        
        //Массив комментариев к посту
        // private set -- говорит о том что массив инкапсулирован
        // и управлять массивом можно только через метод AddComment
        public List<Commentary> Commentaries { get; private set; }

        public News(string text, int writerId, Picture picture) : base(text, writerId)
        {
            Picture = picture;
        }

        public void AddComment(Commentary commentary)
        {
            Commentaries.Add(commentary);
        }
    }

Next, we have role models and each has its own business logic.
2. Subscriber - recipient of news. The business wants every registered user to automatically become a subscriber. This will not happen in the real world, it is impossible, but for example, norms.
3. Writer - one who writes articles/news.
These two models differ only in the role and whether the subscriber has an email field. Therefore, we present here such OOP models
public abstract class User
    {
        public int Id { get; set; }
        public string Username { get; private set; }
        public string Role { get; private set; }
        
        protected User(string role, string username)
        {
            Role = role;
            Username = username;
        }
    }

    public class Subscriber : User
    {
        public string Email { get; private set; }
        
        public Subscriber(string username, string email) : base(nameof(Subscriber), username)
        {
            Email = email;
        }
    }

    public class Writer : User
    {
        public Writer(string username) : base(nameof(Writer), username)
        {
        }
    }

The password field is omitted, a lot of things are omitted here for ease of perception.
3. Comment - feedback from the user in the post. At what I want to note from the USER, the business says that both the subscriber and the writer can write
public class Commentary
    {
        public int Id { get; set; }
        public string CommentText { get; private set; }
        public int UserId { get; private set; }
        
        public virtual User User { get; private set; }
        
        public DateTime CommentCreationDate { get; private set; } 
        
        public Commentary(int userId, string commentText)
        {
            UserId = userId;
            CommentText = commentText;
            CommentCreationDate = DateTime.Now;
        }
    }

Here - although primitive and a little wrong (otherwise programmers will fly in right now), but we described the models, abstracted the same fields into abstract classes. Encapsulated fields and added methods that describe how the class works. Field initialization occurs only in constructors. Working with fields only with the methods provided for this.
I'm sorry that it's not PHP, but C# is also C-like, so there shouldn't be any problems with reading at the model level.
One of the functions of OOP is to make programmers understand business.
Well, it’s prose for a person to describe the behavior of the real world by objects and how these objects interact with each other.
There are whole software development methodologies such as DDD, where the code core is generally written in a coparative language and the rules for naming models and describing business process algorithms are strictly observed. The code is self-documenting. There were cases when the DDD core was even written in Russian, because the business is large, and it was faster and easier for newcomers who came to code in the company to understand the applied business practice and understand how the business works on different layers from the code.

A
Alexander, 2019-07-23
@AleksandrB

everything is shown here

N
Northern Lights, 2019-07-23
@php666

when displaying the bulletin board
....some entity, let's call it Mapper, returns a collection of objects - declaration objects. Each object == one declaration. An ad can have properties - VIP status (end date of this status), typical fields for ads of the title + text type. Next, the ad can have images. The declaration object has a method that asks another entity for its image objects, which in turn know how to form a URL to an image or other image characteristics. The ad object has a getPaymentSystem() method - an object of a Kassa type class is returned, it can return a Robokassa (or Frikassa) object that can generate a URL that is necessary for a payment transaction for paid services of this ad object....
--- this is just a small descriptive part. As an example.
I still don't understand how to use it
and you won't understand without prompting.
Your goal is to open the book "martin fowler architecture of enterprise software applications pdf" to read at least chapters 1, 2, 9 and 10.

D
Demian Smith, 2019-07-23
@search

Book Techniques of object-oriented design. P... provides very popular practices for using OOP. Written in 1994. To this day, it is considered a "must read" for a programmer.

V
Vasily Nazarov, 2019-07-23
@vnaz

OOP for the web is the same as in books.
Make a class PostVBlog
Describe its properties (they are also attributes).
Implement methods for reading and writing from/to the database.
It turns out something like

class BlogPost {
    public $id;
    public $title;
    public $text;
    public $date;
    
    public function write() {
        // код записи в БД
    }
    
    public function read() {
        // код чтения из БД
    }
}

Making a Comment class
class Comment {
    public $id;
    public $text;
    public $date;
    public $blogpostId;
    
    // чёрт, здесь почти такой же код, как и в классе BlogPost
}

You will have to make an ancestor class for BlogPost and Comment
class DatabaseRecord {
    public function write() {
        // универсальный код записи в БД
    }
    
    public function read() {
        // универсальный код чтения из БД
    }
}
class Comment extends DatabaseRecord {
    // ....
}
class Comment extends DatabaseRecord {
    // ....
}

Then go to https://laravel.ru/docs/v5/eloquent and discover with admiration that everything has already been written for you and for you, and just using OOP.

S
Sergey Nizhny Novgorod, 2019-07-24
@Terras

1) Take a framework (Larva or Symphony) and write your web service on it. These frameworks (especially symphony) have design patterns in their base that show you how to use OOP.
2) Read a book on design patterns (Heal Fest Patterns - on the cover is a girl with pigtails) - it will open your eyes.
3) In reality, most of the work is inheritance from abstract classes (most often that the framework provides you), building classes using DI (composition) and that's it =)

I
irishmann, 2019-07-23
@irishmann

Take the framework, according to their documentation, learn how to do it

Blog or Bulletin Board
Along the way, you understand what's what and how. Then you try to implement something of your own without frameworks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question