вызовите один класс из другого. php

#php #class #inheritance

#php #класс #наследование

Вопрос:

У меня есть два класса. Один для приглашения, а другой для уведомления, из которого я отправляю уведомление на устройство.

Я хочу вызвать класс уведомлений, когда приглашение вставляется в базу данных.

Я расширил класс Invitation классом notification, но он не работает, я получаю пустой вывод.

Если я запускаю одно приглашение или один класс уведомлений, оба работают нормально.

Класс приглашения:

  <?php

require 'database.php';
require 'notification.php';

class Invitation extends notification
{
    private $sender_id,$date,$invitee_no,$status,$invitations,$user_name,$contact_id,$contact_name;
    private $notify;

    public function setNotification($message,$user_name) {
        $this->send($message, $user_name); // calling superclass method
    }

    function Invitation($sender_id,$date,$invitee_no,$status,$user_name,$contact_id,$contact_name)
    {

        $this->sender_id = $sender_id;
        $this->date= $date;
        $this->invitee_no = $invitee_no;
        $this->status = $status;
        $this->user_name = $user_name;
        $this->contact_id = $contact_id;
        $this->contact_name = $contact_name;
        // $this -> invitations = $invitations;

    }

    function sendInvite()
    {

        $database = new Database(ContactsConstants::DBHOST, ContactsConstants::DBUSER, ContactsConstants::DBPASS, ContactsConstants::DBNAME);
        $dbConnection = $database->getDB();

        $stmt = $dbConnection->prepare("select * from Invitation where user_name =? and sender_id = ?");
        $stmt->execute(array($this->user_name,$this->sender_id));
        $rows = $stmt->rowCount();


        if ($rows > 0) {
            $response = array("status" => -3, "message" => "Invitation exists.", "user_name" => $this->user_name);
            return $response;
        }

        $this->date = "";
        $this->invitee_no = "";
        $this->status = "0";
        $this->contact_id = 0;
        $this->contact_name = "";

        echo $this->user_name;
        echo $this->sender_id;

        $stmt = $dbConnection->prepare("insert into Invitation(sender_id,date,invitee_no,status,user_name,contact_id,contact_name) values(?,?,?,?,?,?,?)");

        $stmt->execute(array($this->sender_id, $this->date, $this->invitee_no, $this->status, $this->user_name,$this->contact_id,$this->contact_name));

        $rows = $stmt->rowCount();
        $Id = $dbConnection->lastInsertId();


        $stmt = $dbConnection->prepare("select * from Invitation where invitation_id=?");
        $stmt->execute(array($Id));
        $invitation = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($rows < 1) {

            $response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason");
            return $response;

        } else {


          //  $notify = new notification();
          //  $resp = $notify->send($message, $this->user_name);

            $response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation);
            return $response;

        }

    }
 

уведомление:

     <?php

require 'database.php';

class notification
{

    private $text,$user_name;

    public function __construct()
    {
    }

    public function send($text,$userName)
    {

        $database = new Database(ContactsConstants::DBHOST, ContactsConstants::DBUSER, ContactsConstants::DBPASS, ContactsConstants::DBNAME);
        $dbConnection = $database->getDB();

        $stmt = $dbConnection->prepare("Select device_id from Users where user_name =?");
        $stmt->execute(array($userName));

        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $token = $result["device_id"];

       // echo $token;
       // echo $text;
       // echo $userName;

        if(!empty($token)) {
            echo $token;
            $response = $this->sendPush($text, $token, "AIzaSyBGwwJaThyLm-PhvgcbdYurj-bYQQ7XmCc");
        }
    }

    public function sendPush($text, $tokens, $apiKey)
    {

        $notification = array(
            "title" => "You got an invitation.",
            "text" => $text,
            "icon" => "ic_chat_bubble_white_48dp",
            'vibrate' => 3,
            'sound' => "default"
        );

        $msg = array
        (
            'message' => $text,
            'title' => 'You got an invitation.',
            'tickerText' => 'New Message',
            'largeIcon' => 'large_icon',
            'smallIcon' => 'small_icon'
        );
        $fields = array
        (
            'to' => $tokens,
            'data' => $msg,
            'notification' => $notification
        );

        $headers = array
        (
            'Authorization: key=' . $apiKey,
            'Content-Type: application/json'
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        $result = curl_exec($ch);
        echo($result);
        return $result;
        curl_close($ch);
    }
}
?>
 

Скрипт отправки приглашения:

     <?php

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');

require 'Invitation.php';
require 'notification.php';


$jsonText = file_get_contents('php://input');

if(empty($jsonText))
{
    $response = array("status"=>-2,"message"=>"Empty request");
    die(json_encode($response));
}

$json = json_decode($jsonText);

$sender_id = $json-> sender_id;
$user_name = $json -> user_name;


echo $sender_id;
echo $user_name;

$invitation = new Invitation($sender_id,"","","",$user_name,"","");
$response = $invitation->sendInvite();

$message =  'Hi,add me to your unique contact list and you never need to update any changes anymore!';

$invitation->setNotification($message,$user_name);

echo(json_encode($response));
?>
 

How to integrate this?

EDIT:

I changed require to require_once

updated code:

Invitation:

   <?php

require_once 'database.php';

require_once 'notification.php';

class Invitation extends notification
{
    private $sender_id,$date,$invitee_no,$status,$invitations,$user_name,$contact_id,$contact_name;
    private $notify;

    public function setNotify($message,$user_name) {
        $this->send($message, $user_name); // calling superclass method
    }

    function Invitation($sender_id,$date,$invitee_no,$status,$user_name,$contact_id,$contact_name)
    {

        $this->sender_id = $sender_id;
        $this->date= $date;
        $this->invitee_no = $invitee_no;
        $this->status = $status;
        $this->user_name = $user_name;
        $this->contact_id = $contact_id;
        $this->contact_name = $contact_name;
        // $this -> invitations = $invitations;

    }

    function sendInvite()
    {

        $database = new Database(ContactsConstants::DBHOST, ContactsConstants::DBUSER, ContactsConstants::DBPASS, ContactsConstants::DBNAME);
        $dbConnection = $database->getDB();

        $stmt = $dbConnection->prepare("select * from Invitation where user_name =? and sender_id = ?");
        $stmt->execute(array($this->user_name,$this->sender_id));
        $rows = $stmt->rowCount();


        if ($rows > 0) {
            $response = array("status" => -3, "message" => "Invitation exists.", "user_name" => $this->user_name);
            return $response;
        }

        $this->date = "";
        $this->invitee_no = "";
        $this->status = "0";
        $this->contact_id = 0;
        $this->contact_name = "";

        $stmt = $dbConnection->prepare("insert into Invitation(sender_id,date,invitee_no,status,user_name,contact_id,contact_name) values(?,?,?,?,?,?,?)");

        $stmt->execute(array($this->sender_id, $this->date, $this->invitee_no, $this->status, $this->user_name,$this->contact_id,$this->contact_name));

        $rows = $stmt->rowCount();
        $Id = $dbConnection->lastInsertId();

        $stmt = $dbConnection->prepare("select * from Invitation where invitation_id=?");
        $stmt->execute(array($Id));
        $invitation = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($rows < 1) {

            $response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason");
            return $response;

        } else {


          //  $notify = new notification();
          //  $resp = $notify->send($message, $this->user_name);

            $response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation);
            return $response;

        }
    }
 

notification:

 require_once 'database.php';

class notification
{

    private $text,$user_name;

    public function __construct()
    {

    }
    public function setNotification($text, $username) {
        $this->text = $text;
        $this->user_name = $username;
    }
    public function send($text, $username)
    {

        $database = new Database(ContactsConstants::DBHOST, ContactsConstants::DBUSER, ContactsConstants::DBPASS, ContactsConstants::DBNAME);
        $dbConnection = $database->getDB();

        $stmt = $dbConnection->prepare("Select device_id from Users where user_name =?");
        $stmt->execute(array($this->username));

        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $token = $result["device_id"];

        echo $token;
        echo $this->text;
        echo $this->username;

        if(!empty($token)) {
            echo $token;
            $response = $this->sendPush($this->text, $token, "AIzaSyBGwwJaThyLm-PhvgcbdYurj-bYQQ7XmCc");
        }
    }

    public function sendPush($text, $tokens, $apiKey)
    {

        $notification = array(
            "title" => "You got an invitation.",
            "text" => $text,
            "icon" => "ic_chat_bubble_white_48dp",
            'vibrate' => 3,
            'sound' => "default"
        );

        $msg = array
        (
            'message' => $text,
            'title' => 'You got an invitation.',
            'tickerText' => 'New Message',
            'largeIcon' => 'large_icon',
            'smallIcon' => 'small_icon'
        );
        $fields = array
        (
            'to' => $tokens,
            'data' => $msg,
            'notification' => $notification
        );

        $headers = array
        (
            'Authorization: key=' . $apiKey,
            'Content-Type: application/json'
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        $result = curl_exec($ch);
        echo($result);
        return $result;
        curl_close($ch);
    }
}
?>
 

sendInvite:

     <?php

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');

require_once 'Invitation.php';

$jsonText = file_get_contents('php://input');

if(empty($jsonText))
{
    $response = array("status"=>-2,"message"=>"Empty request");
    die(json_encode($response));
}

$json = json_decode($jsonText);

$sender_id = $json-> sender_id;
$user_name = $json -> user_name;


echo $sender_id;
echo $user_name;

$invitation = new Invitation($sender_id,"","","",$user_name,"","");
$response = $invitation->sendInvite();

$message =  'Hi,add me to your unique contact list and you never need to update any changes anymore!';

$invitation->setNotification($message,$user_name);


echo(json_encode($response));
?>
 

Теперь получаем вывод следующим образом:

 <!DOCTYPE html>
<html lang=en>
    <meta charset=utf-8>
    <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
    <title>Error 404 (Not Found)!!1</title>
    <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
  </style>
    <a href=//www.google.com/>
    <span id=logo aria-label=Google></span>
</a>
<p>
    <b>404.</b>
    <ins>That’s an error.</ins>
    <p>The requested URL 
        <code>/fcm/send</code> was not found on this server.
        <ins>That’s all we know.</ins>
{"status":1,"message":"Invitation sent.","Invitation:":{"invitation_id":"547","date":"","invitee_no":"","status":"0","sender_id":"50","contact_id":"0","user_name":"siddhi","contact_name":""}}
 

Пожалуйста, помогите.. Спасибо..

Комментарии:

1. Вам не требуется require 'database.php'; на странице приглашения, так как это приведет к фатальной ошибке. Точно так же вам не нужно включать require 'notification.php'; в скрипт sendInvite.

2. Я хочу получить доступ к соединению с базой данных в других функциях класса invitation. Итак, для этого мне нужно ‘database.php — на уроке приглашений. не могли бы вы показать мне, как я могу это сделать? @ASR

Ответ №1:

Объявите переменную класса внутри файла уведомлений следующим образом и вызовите database в функции construct . Используйте $this->dbConnection вместо $dbConnection всех других мест.

 class notification
{

    private $text,$user_name;
    public $dbConnection

    public function __construct()
    {
            $database = new Database(ContactsConstants::DBHOST, ContactsConstants::DBUSER, ContactsConstants::DBPASS, ContactsConstants::DBNAME);
            $this->dbConnection = $database->getDB();
    }

    public function send($text,$userName)
    {
        $stmt = $this->dbConnection->prepare("Select device_id from Users where user_name =?");
        $stmt->execute(array($userName));

        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $token = $result["device_id"];
 

Затем по приглашению php удалите require 'database.php'; строку и получите доступ к функциям базы данных, используя $this->dbConnection

  function sendInvite()
    {

        $stmt = $this->dbConnection->prepare("select * from Invitation where user_name =? and sender_id = ?");
        $stmt->execute(array($this->user_name,$this->sender_id));
        $rows = $stmt->rowCount();
 

И в условии else вам не нужно повторно объявлять класс ‘notification’ снова, просто получите к нему доступ следующим образом.

  $resp = $this->send($message, $this->user_name);
 

Надеюсь, это поможет.

Комментарии:

1. Нужно ли мне расширять класс уведомлений или нет? @ASR

2. Да, вы должны расширить class Invitation extends notification

Ответ №2:

измените require на require_once, чтобы избежать проблем с включением.

Комментарии:

1. изменение этого класса приглашения привело к выполнению, но не к классу уведомлений. @Kris Roofe

2. Вы изменили все свои требования в этих файлах? И о какой ошибке сообщалось?

3. не могли бы вы проверить отредактированный вопрос?@ Крис Руф