php – OOP: The correct use of classes and optimizing code

I am trying to improved my coding skills. I mainly work in web development. I had a “system” that I use in all my projects to fetch data from my DB to the browser. I tried an implementation of OOP, it works fine, but I dont think I did it correctly.

How can I optimized this code to make full use of an OOP design?

<?php
  class DBX{

    //---------------USER-----------------------------

    static function GetUserByEmail($email){
      $link = openlink();
      $query = "SELECT * FROM users WHERE email = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "s", $email);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_assoc();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetUserByID($id){
      $link = openlink();
      $query = "SELECT * FROM users WHERE user_id = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "i", $id);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_assoc();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetUsers(){
      $link = openlink();
      $query = "SELECT * FROM users";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetClients(){
      $link = openlink();
      $l = 4;
      $query = "SELECT * FROM users WHERE access_level_id = ?";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "i", $l);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function AddUser(
      $f_name,
      $l_name,
      $ll_name,
      $email,
      $access_level,
      $status,
      $phone,
      $joinDate,
      $clientNum,
      $hashedPW
    ){
      $link = openlink();
      $query = "INSERT INTO users (
        name,
        l_name,
        ll_name,
        phone,
        email,
        status,
        access_level_id,
        join_date,
        contract_id,
        password
      )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param(
          $stmt,
          "sssssiisss",
          $f_name,
          $l_name,
          $ll_name,
          $phone,
          $email,
          $status,
          $access_level,
          $joinDate,
          $clientNum,
          $hashedPW
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function UpdateUser($id, $userInfo){
      $link = openlink();
      $query = "UPDATE users SET
        name = ?,
        l_name = ?,
        ll_name = ?,
        email = ?,
        access_level_id = ?,
        phone = ?,
        status = ?,
        join_date = ?,
        contract_id = ?,
        password = ?
        WHERE user_id = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param(
          $stmt,
          "ssssisisssi",
          $userInfo('name'),
          $userInfo('l_name'),
          $userInfo('ll_name'),
          $userInfo('email'),
          $userInfo('access_level_id'),
          $userInfo('phone'),
          $userInfo('status'),
          $userInfo('join_date'),
          $userInfo('contract_id'),
          $userInfo('password'),
          $id
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = "false5";
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function UpdateUserPasswordByID($password, $id){
      $link = openlink();
      $query = "UPDATE users SET
        password = ?
        where user_id = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      } else {
        mysqli_stmt_bind_param(
          $stmt,
          "si",
          $password,
          $id
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    //---------------ACCESS LEVELS-----------------------------

    static function GetAccessLevels(){
      $link = openlink();
      $query = "SELECT * FROM access_levels";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    //---------------Follow Ups-----------------------------

    static function GetFUByUserID($id){
      $link = openlink();
      $query = "SELECT * FROM follow_up WHERE user_id = ? ORDER BY created_at DESC";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "i", $id);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function AddFu($targetID, $senderID, $type, $message){
      $link = openlink();
      $date = date("Y-m-d H:i:s");
      $query = "INSERT INTO follow_up (user_id, created_by, created_at, type, message) VALUES (?, ?, ?, ?, ?)";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "iisis", $targetID, $senderID, $date, $type, $message);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }











    //-------REPURPUSING Pool

    //---------------USER-----------------------------



    static function QuickAddUser($email, $f_name, $l_name, $ll_names, $hashedPW){
      $link = openlink();
      $status = 1;
      $accessLevel = 8;
      $query = "INSERT INTO users (email, f_name, l_name, ll_name, password, status, access_level_id)
        VALUES (?, ?, ?, ?, ?, ?, ?)";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param(
          $stmt,
          "sssssii",
          $email,
          $f_name,
          $l_name,
          $ll_names,
          $hashedPW,
          $status,
          $accessLevel
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }




    static function GetUserByUsername($username){
      $link = openlink();
      $query = "SELECT * FROM users WHERE username = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "s", $username);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_assoc();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetUsersByNames($string){
      $link = openlink();
      $string = "%".$string."%";
      $query = "SELECT * FROM users WHERE f_name LIKE ? OR l_name LIKE ? OR ll_name LIKE ?";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "sss", $string, $string, $string);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetStudentsByGroupID($groupID){
      $link = openlink();
      $query = "SELECT * FROM users WHERE group_id = ? ORDER BY l_name DESC";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "i", $groupID);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetStudentsBySchoolYearID($yearID){
      $link = openlink();
      $query = "SELECT * FROM users WHERE grado_id = ? ORDER BY l_name DESC";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "i", $yearID);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetFamilyByChildID($userID){
      $link = openlink();
      $query = "SELECT * FROM family_student WHERE student_id = ?";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "i", $userID);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetChildrenByFamilyID($userID){
      $link = openlink();
      $query = "SELECT * FROM family_student WHERE family_member_id = ?";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "i", $userID);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetUserByIDArray($id){
      $link = openlink();
      $query = "SELECT * FROM users WHERE user_id = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "i", $id);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetUsersByAccessLevel($accessLevel){
      $link = openlink();
      $query = "SELECT * FROM users WHERE access_id = ? ORDER BY l_name DESC";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "i", $accessLevel);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function linkToStudentByTargetUserID($id, $studentID){
      $link = openlink();
      $query = "INSERT INTO family_student (student_id, family_member_id) VALUES (?, ?)";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      } else {
        mysqli_stmt_bind_param(
          $stmt,
          "ii",
          $studentID,
          $id
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function UnlinkStudent($id, $studentID){
      $link = openlink();
      $query = "DELETE FROM family_student WHERE student_id = ? AND family_member_id = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      } else {
        mysqli_stmt_bind_param(
          $stmt,
          "ii",
          $studentID,
          $id
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function AddStudentToGroup($groudID, $studentID){
      $link = openlink();
      $query = "UPDATE users SET
        group_id = ?
        where user_id = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      } else {
        mysqli_stmt_bind_param(
          $stmt,
          "ii",
          $groudID,
          $studentID
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function UpdateUserPhotoByID($photoLoc, $id){
      $link = openlink();
      $query = "UPDATE users SET
        profile_photo = ?
        where user_id = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      } else {
        mysqli_stmt_bind_param(
          $stmt,
          "si",
          $photoLoc,
          $id
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function UpdateUserStatusByID($id, $status){
      $link = openlink();
      if ($status) {
        $tempStatus = 1;
      } else {
        $tempStatus = 0;
      }

      $query = "UPDATE users SET
        status = ?
        where user_id  = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      } else {
        mysqli_stmt_bind_param(
          $stmt,
          "ii",
          $tempStatus,
          $id
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    //---------------SCHOOL GRADE YEARS-----------------------------

    static function AddSchoolYear($yearName){
      $link = openlink();
      $status = 1;
      $query = "INSERT INTO grados ( name, status) VALUES (?, ?)";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "si", $yearName, $status);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetSchoolYearGrades(){
      $link = openlink();
      $query = "SELECT * FROM grados";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_all();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function GetSchoolYearByID($id){
      $link = openlink();
      $query = "SELECT * FROM grados WHERE grados_id  = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "i", $id);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $resultArray = $result->fetch_assoc();
          $finalTest = $resultArray;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function UpdateSchoolYear($id, $year){
      $link = openlink();
      $query = "UPDATE grados SET
        name = ?
        WHERE grados_id   = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      } else {
        mysqli_stmt_bind_param(
          $stmt,
          "si",
          $year('name'),
          $id
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    static function UpdateSchoolYearStatusByID($id, $status){
      $link = openlink();
      if ($status) {
        $tempStatus = 1;
      } else {
        $tempStatus = 0;
      }

      $query = "UPDATE grados SET
        status = ?
        where grados_id = ? LIMIT 1";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      } else {
        mysqli_stmt_bind_param(
          $stmt,
          "ii",
          $tempStatus,
          $id
        );
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }

    //---------------ACCESS LEVELS-----------------------------


    static function AddAccessLevel($yearName){
      $link = openlink();
      $query = "INSERT INTO acess_levels (name) VALUES (?)";
      $stmt = mysqli_stmt_init($link);
      if (!mysqli_stmt_prepare($stmt, $query)) {
        //return false if there was an error
        return false;
      }else {
        mysqli_stmt_bind_param($stmt, "s", $yearName);
        if (mysqli_stmt_execute($stmt)) {
          $result = $stmt->get_result(); // get the mysqli result
          $finalTest = true;
        } else {
          $finalTest = false;
        }
      }
      closeLink($stmt, $link);
      return $finalTest;
    }
  }

  //open link
  include 'dbConnect.inc.php';

  //closing link
  function closeLink($stmt, $link){
    mysqli_stmt_close($stmt);
    mysqli_close($link);
  }
  //date("Y-m-d H:i:s")
?>

As you can see I repeat most of the code over and over, I think I could do one method for each CRUD and then somehow just pass the differences… any ideas??

multi classing – Does a PF2e spellcaster who takes multiclass dedications into other spellcasting classes, and related spellcasting feats, gain more spell slots?

Ezren is a level 10 evocation wizard, and hence would have spell slots of the following levels:

+-------------+-----------------+
| Spell level | Number of slots |
+-------------+-----------------+
|           1 |               4 |
|           2 |               4 |
|           3 |               4 |
|           4 |               4 |
|           5 |               4 |
+-------------+-----------------+

However, at level 2 Ezren took the Sorcerer multiclass dedication. At level 4 he took Basic Sorcerer Spellcasting, and Bloodline Breadth at level 8.

How many spell slots does Ezren have in a given day? Is it:

+-------------+-----------------+
| Spell level | Number of slots |
+-------------+-----------------+
|           1 |               6 |
|           2 |               6 |
|           3 |               6 |
|           4 |               4 |
|           5 |               4 |
+-------------+-----------------+

Because at level 8, spellcasting archetype feats grant an additional spell slot of first, second and third level, AND the bloodline breadth feat increases each of these by one?

Or do these sources of spell slots not stack for some reason? Coming from fifth edition, a wizard who multiclasses sorcerer still has the same number of spell slots as a pure wizard, so I’d like to clarify my understanding here.

design – Why are Description classes useful in oop

“If an item in the inventory is sold or deleted, the stock count will be updated from the database” –

It’s not about that. This is not a generalized OOP recommendation, this is about the kinds of relationships that arise in certain domains.

If an item is sold out, you still can go to the database and query the price or details of that product. The table that stores product details, as well as the stock count is a description of a product. But sometimes it’s not enough to just store the count, sometimes you need extra data, perhaps better represented by a separate table or an object. Again, this whole discusion is not really related to OOP itself, it’s about domain modeling.

E.g., suppose you’re selling stuff online. You may want to keep generalized product descriptions & specs (something that people might search for) separate from data about the concrete items you have on stock (e.g., these might store info on whether the item is new or second-hand, if it’s damaged, a note about the item itself, etc.)

java – Como trabalhar com Classes que tenham outras Classes como atributo SpringBoot

Eae gente , essa é primeira vez que to programando pra web e to usando o spring boot pra isso , é um projeto da faculdade onde o FrontEnd vai ser feito em JS com React e o Back feito em JAVA com Spring . com o banco de dados postgres.
Eu fiquei com o Back end , e tudo ia bem até eu precisar trabalhar com classes compostas (classes que tem outras classes como atributo).
Tenho que fazer meio que uma lista de compra , uma Classe carrinho que tem como atributo um arrayList de compras , no qual compra tem como atributo um produto.

package com.api.springboot.model;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.hibernate.annotations.Cascade;
import org.springframework.data.annotation.CreatedDate;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "carrinhos")
public class Carrinho implements Serializable {

    private static final long serialVersonUID = 1L;

    public Carrinho() {
        this.terminado = false;
    }


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String nome;
    private boolean terminado;
    private float precoTotal;


    @OneToMany
            //(cascade = CascadeType.ALL, mappedBy = "carrinhos")
    @JoinColumn(name = "carrinho_id")
    private List<Compra> compras = new ArrayList<>();

    @ManyToOne
    private Comprador comprador;

    @CreatedDate
    private Date criadoEm = new Date();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public boolean isTerminado() {
        return terminado;
    }

    public void setTerminado(boolean terminado) {
        this.terminado = terminado;
    }

    public float getPrecoTotal() {
        return precoTotal;
    }

    public void setPrecoTotal(float precoTotal) {
        this.precoTotal = precoTotal;
    }

    public void setCriadoEm(Date criadoEm) {
        this.criadoEm = criadoEm;
    }

    public List<Compra> getCompras() {
        return compras;
    }

    public void setCompras(List<Compra> compras) {
        this.compras = compras;
    }

    public void adicionarCompra(Compra compra){
        this.compras.add(compra);
    }

    public Date getCriadoEm() {
        return criadoEm;
    }

    public Comprador getComprador() {
        return comprador;
    }

    public void setComprador(Comprador comprador) {
        this.comprador = comprador;
    }

    public void add(Compra compra){
        compras.add(compra);
    }

    @Override
    public String toString() {
        return "Carrinho{" +
                "id=" + id +
                "n, nome='" + nome + ''' +
                "n, terminado=" + terminado +
                "n, precoTotal=" + precoTotal +
                "n, compras=" + compras +
                "n, comprador=" + comprador +
                "n, criadoEm=" + criadoEm +
                '}';
    }


}


package com.api.springboot.model;
import org.hibernate.annotations.ManyToAny;
import org.springframework.data.annotation.CreatedDate;

import javax.persistence.*;
import java.io.Serializable;
import java.time.*;
import java.util.Date;

@Entity
@Table(name = "compras")
public class Compra implements Serializable {


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "produto_id")
    private Produto produto = new Produto();

    private int quantidade;
    private float precoTotal;

    @ManyToOne
    @JoinColumn(name = "carrinho_id")
    private Carrinho carrinho;

    @OneToOne
    private Promocao promocao;

    @CreatedDate
    private Date criadoEm = new Date();

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public Produto getProduto() {
        return produto;
    }

    public void setProduto(Produto produto) {
        this.produto = produto;
    }

    public int getQuantidade() {
        return quantidade;
    }

    public void setQuantidade(int quantidade) {
        this.quantidade = quantidade;
    }

    public float getPrecoTotal() {
        return precoTotal;
    }

    public void setPrecoTotal(float precoTotal) {
        this.precoTotal = precoTotal;
    }

    public Date getCriadoEm() {
        return criadoEm;
    }

    public Promocao getPromocao() {
        return promocao;
    }

    public void setPromocao(Promocao promocao) {
        this.promocao = promocao;
    }

    public void setCriadoEm(Date criadoEm) {
        this.criadoEm = criadoEm;
    }

    public Carrinho getCarrinho() {
        return carrinho;
    }

    public void setCarrinho(Carrinho carrinho) {
        this.carrinho = carrinho;
    }

    @Override
    public String toString() {
        return "Compra{" +
                "id=" + id +
                ", produto=" + produto +
                ", quantidade=" + quantidade +
                ", precoTotal=" + precoTotal +
                ", carrinho=" + carrinho +
                ", promocao=" + promocao +
                ", criadoEm=" + criadoEm +
                '}';
    }
}


´´´
´´´
package com.api.springboot.model;

import org.springframework.data.annotation.CreatedDate;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Date;

@Entity
@Table(name = "produtos")
public class Produto {
    private static final long serialVersonUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String nome;
    private float preco;
    private float peso;
    private boolean tipo;

    @ManyToOne
    private Categoria categoria;

    @CreatedDate
    private Date criadoEm = new Date();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() { return nome; }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public float getPreco() {
        return preco;
    }

    public void setPreco(float preco) {
        this.preco = preco;
    }

    public float getPeso() {
        return peso;
    }

    public void setPeso(float peso) {
        this.peso = peso;
    }

    public boolean isTipo() {
        return tipo;
    }

    public void setTipo(boolean tipo) {
        this.tipo = tipo;
    }

    public Date getCriadoEm() {
        return criadoEm;
    }

    public Categoria getCategoria() {
        return categoria;
    }

    public void setCategoria(Categoria categoria) {
        this.categoria = categoria;
    }

    @Override
    public String toString() {
        return "Produto{" +
                "id=" + id +
                ", nome='" + nome + ''' +
                ", preco=" + preco +
                ", peso=" + peso +
                ", tipo=" + tipo +
                ", categoria=" + categoria +
                ", criadoEm=" + criadoEm +
                '}';
    }
}

Essas são as 3 classes principais vou colocar somente o controlador de carrinho pois se me ajudarem com ele acredito que consigo usar a lógica para os outros.

package com.api.springboot.controllers;

import com.api.springboot.model.Carrinho;
import com.api.springboot.model.Compra;
import com.api.springboot.repository.CarrinhoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api")
public class CarrinhoController {

    @Autowired
    CarrinhoRepository carrinhoRepository;

    @GetMapping("/carrinhos")
    public List<Carrinho> listarCompras(){
        return carrinhoRepository.findAll();
    }

    @GetMapping("/carrinho/{id}")
    public Carrinho carrinhoById(@PathVariable(value = "id") long  id){
        return carrinhoRepository.findById(id);
    }

    @PostMapping("/carrinho")
    public Carrinho salvarCarrinho(@RequestBody Carrinho carrinho){
        return carrinhoRepository.save(carrinho);
    }

    @DeleteMapping("/carrinho")
    public void deletaCarrinho(@RequestBody Carrinho carrinho){
        carrinhoRepository.delete(carrinho);
    }

    @DeleteMapping("/carrinho/{id}")
    public void deletetById(@PathVariable(value = "id")long id){
        carrinhoRepository.deleteById(id);
    }

    @PutMapping("/carrinho/put")
    public Carrinho atualizarCarrinho(@RequestBody Carrinho carrinho){
        return carrinhoRepository.save(carrinho);
    }


    @PostMapping("/teste/{id}")
    public void add(@PathVariable(value = "id") long id , @RequestBody Compra x){
        Carrinho instancia = carrinhoRepository.findById(id);
        System.out.println(instancia);
        System.out.println(x);
//        instancia.add();
//        carrinhoRepository.save(instancia);
//        System.out.println("Rodou o dream do dream quero");
//        System.out.println(instancia);
    }

}

A minha dúvida é , como que eu adiciono uma compra em carrinho . Eu tentei usar a compra x vindo do front como parâmetro e adicionar ela , só que ela vem nula.
inserir a descrição da imagem aqui
Aí uma foto de como chega , eu nunca usei injeção de dependências e todos os tutorias os professores só usam classes com atributos de tipo int,String,boolean …

ag.algebraic geometry – The isomorphism classes of lifts of a $operatorname{PGL}_r$-bundle to $operatorname{GL}_r$

I want to show the following Lemma,

The set of algebraic isomorphism classes of lifts to $operatorname{GL}_r$ of an algebraic principal $operatorname{PGL}_r$ -bundle $P$ on a smooth projective curve $X$ over $mathbb{C}$ is an $H^1(X,mathcal{O}_{X}^*)$ torsor.

Let $rho:operatorname{GL}_rrightarrow operatorname{PGL}_r$. By difinition, the lift of $P$ is a $(P^{operatorname{GL}_r},zeta)$, a pair consisting of a $operatorname{GL}_r$-bundle $P^{operatorname{GL}_r}$ and an isomorphism $zeta:rho_{*}P^{operatorname{GL}_r}cong P$
$H^1(X,mathcal{O}_X^*)cong check{H}{^1}(X,mathcal{O}_X^{*})$.Then, I want a the action of $check{H}{^1}(X,mathcal{O}_X^{*})$ on the set of lifts.
Let $(P^{operatorname{GL}_r},zeta)$ be a lift and $ain check{H}{^1}(X,mathcal{O}_X^{*})$. Let ${g_{ij}}$ be $operatorname{GL}_r$-cocycle representing the isomorphism class of $P^{operatorname{GL}_r}$, and ${a_{ij}}$ be a $mathcal{O}_X$-cocycle representing $a$.

Then, How can I check that ${g_{ij}a_{ij}}$ defines a principal $operatorname{GL}_r$-bundle $P^{‘}$, and how can I construct an isomorphism $zeta^{‘}:rho_{*}P^{‘}cong P$ ?
In addition, is this action simply transitively ?

Thanks in advence.

co.combinatorics – Additional Examples of Classes of Networks whose Hasse diagram of the Poset is a Perfect Graph

This question is very important for my research, which is why I ask it here.
I do not have a formal background in graph theory so please excuse me if I state a term incorrectly (and feel free to correct me).

Suppose I have a directed acyclic network with a source node $s$ and a sink node $t$. Suppose I construct a corresponding partially ordered set as follows:

  1. The elements of the partially ordered set are edges of the directed acyclic graph.
  2. Elements are comparable in the sense that two elements are comparable if there is an $s-t$ path between the two edges in the network. For example, $1 preceq 2 preceq 3$ means that there is an $s-t$ path consisting of edges $e_{1}$,$e_{2}$, $e_3$ in that order.
  3. Thus, the maximal chains of the partially ordered set are the $s-t$ paths of the directed acyclic network.

Consider the Hasse diagram of the partially ordered set described above. Although, a Hasse diagram is technically a diagram not an undirected graph, we consider it as an undirected graph.

My Question then is: For what general classes or types of networks or directed acyclic graphs (the directed version is acyclic) is the corresponding Hasse diagram, associated with the partially ordered set, a perfect graph?

Recall, a graph is a perfect, by the Strong Perfect Graph Theorem, if is neither is not contains an induced odd cycle or antihole of length $5$ or more.

I believe, that series-parallel networks are one type of network which fit the above description. That is, the Hasse diagram is perfect of such networks.

I believe this is the case because there is no fence or zig-zag in the Hasse diagram corresponding to the poset associated with Series-Parallel networks (or at least there is some relation there).
See:https://en.wikipedia.org/wiki/Fence_(mathematics).

Interestingly, as wikipedia describes, a partially ordered set is series-parallel if and only if it does not have four elements forming a fence. Perhaps, the reason then the Hasse diagram is perfect is because it has no induced $P_4$. (I think there is a relation between “fence” in the poset and no induced $P_{4}$ of the corresponding Hasse diagram).

These are just some thoughts, I am not completely sure if what I have said is correct.

Of course, a graph can be perfect even if it has an induced $P_4$ (although if it does not have an induced $P_4$ then it is perfect).

My question then remains, what is another example of directed acyclic graphs, or networks, besides series-parallel, where the corresponding Hasse diagram of the poset is a perfect graph?

I feel that there should exist another class of such graphs but I have been unable to find one after a long time scouring the internet. Since I am not a researcher in graph theory, it has been really tough for me to find such a class of dag’s or networks.

If another class of directed acyclic graph or networks does not exist, does there exist an example of a class of directed cyclic graph with the above properties?

Note, in the above questions, I am looking for classes of graphs, not a particular instance.

This question is very crucial for my research and I really appreciate any thoughts, guidance, or just anything at all that could at least point me in the right direction as I have been stuck for quite some time.
thanks.

classes – Python: Função em módulo dando problema pra executar no programa principal

iae pessoal, estou com um mini projeto de quarentena, que serve para ter o controle de produtos em um mercadinho, tenho um módulo “classes” que tem a classe vendas que tem a minha def que serve para adicionar quantidade de produtos no estoque de um produto já existente que não está executando o esperado…

class vendas:
    def __init__(self, ide, quantide):
        self._banco = sqlite3.connect('bancoProd.db')
        self._cursor = self._banco.cursor()
        self._id = ide
        self._quantide = quantide
    

    def adicionar_estoque(self):
        self._cursor.execute(f"UPDATE produtos SET quantidade = {self._quantide} WHERE id = {self._id}")
        print('énois mudados no esqotque')

    
    def agr_foi(self):
        self._banco.commit()
        print('énois adicionando estoque')

e no meu programa principal eu estou tentando chamar assim:

t = classes.vendas(1, 2)
t.adicionar_estoque()
t.agr_foi()

ela executa, não mostra os prints das defs, e não da erro quando executa…

design – “Assign” Role Association between two classes

If there is Class A and Class B and there is an association that B can be assigned to A.And the multiplicity is 1:M or M:1 from A to B.Example:

1.Room has Collection of Keys, and Key can can assigned to Room.

2.Match has a Referee, and Referee can be assigned to Collection of Matches.

I want to know, what would be correct place to put an assign Method?

In example 1, Room should have an assign(RoomKey) Method or RoomKey should have assingToRoom(Room) method?Are both ways correct?

c# – How to deal with references to shared manager classes

I am using C# with MonoGame, although this is relevant for any object-oriented programming language

Static classes should be reserved for stateless utility classes (for example System.Math) and they should generally be avoided along with singletons for manager-like classes. The reason for this is it prevents object-oriented strategies and may be under the false pretense that there is only one instance required at all times.

To solve these issues you could have instances like AudioManager, EffectManager, Time, etc. in a single global static object. But this does not solve another issue which is you do not control who has access to these instances. So instead pass in these instances from the top down through constructors to classes who need to access certain things.

In my game I have an entity component system. Character derives from Actor which derives from Component which is contained within an Entity. When a Character gets hit I want time to stop briefly (Time instance), the camera should shake (Camera instance), he should flash white (Effects instance), Damage text should be spawned (FloatingText instance) and a sound effect should be emitted (AudioManager instance).

This is just one example and child classes may need more things or pass in different parameters to these instances. Additionally, anyone higher up the hierarchy will need more instance references if they need to pass it down to someone who is lower down.

Q: “What is the problem in that?” A: “It is cumbersome and I am modifying an entire hierarchy when I want to change something one place”

If I realize a component needs a reference to another instance I need to modify the code throughout the entire hierarchy. A solution is to make the global static object itself a non-static instance and pass down the whole thing to all components (but I might only pass down a certain instance to other parts of the game).

“Maybe you just have a coupling problem? Character should not be the one to stop time, shake camera, etc.”

Okay, who should then? I could use an OnHit event in Character and let AudioManager for example hook up to that for all characters and play a sound effect with different parameters depending on the type of Character. But now I need to make a switch statement on type inside AudioManager, not very object-oriented. Instead, I could have one request manager instance to all of these things that takes in a parameter list as well. But what is the difference between this and a shared object instance? Anyone with a reference to request manager can make any request it’s just a bit more indirect.

Passing in a container to all shared instances in the constructor of e.g. Component seems like the best compromise. What do you think?

messaging – Common library for classes and communication between microservices?

I have been working on a project that is being built around a microservices architecture. We are thinking on using a message broker, such as RabbitMQ, for both synchronous (via RPC) and asynchronous communication between services.

The team is constituted of Java developers, and all of the services are Spring Boot.

Suppose the following scenario:

  1. ServiceA needs to know the address to connect to the RabbitMQ server, and its credentials. ServiceA posts a message to an exchange in the message broker. This payload is built of ClassA serialized as JSON.
  2. ServiceB also needs to know the address to connect to the same RabbitMQ server, and its credentials. ServiceB is subscribed to the same exchange as ServiceA a consumer. ServiceB also needs to have ClassA within the project so that it can deserialize the payload sent by ServiceA.

We dont want to couple or duplicate data/functionality so that we can reuse things as much as possible.

With the current approach we are duplicating the classes between services, so that they can serialize/deserialize it. Also, we are duplicating the information necessary to connect to the RabbitMQ server, and publish/consume messages.

What is the standard approach to this? I feel that this is a common problem of microservice projects but could not find a pragmatic answer yet.

  1. Should we externalize this classes used for serialization/deserialization to a common library? Do microservices architecture have a standard name for such library?
  2. Should we also create a library to share the RabbitMQ server connection info, and credentials, between the services?
  3. Where should the pub/sub logic be? Should we leave each microservice to import the RabbitMQ client dependency, or should we create a library that “teaches” the microservices how to pub/sub certain messages?