mardi 27 novembre 2018

creating laravel helper [class facade not fount]

I'm trying to create my first facade, I follow the documentation, but end up with this error: ErrorException (E_WARNING) Class 'App\Facades\CustomDB' not found, I am trying to make a class like the one that is called DB in laravel, it's named CustomDB

This is my CustomDB.php located in (App\Helpers\DB):

namespace App\Helpers\DB;

class CustomDB {
    private static $_instance = null; //store instance of the database if it is available
    private $_pdo,
            $_query,
            $_error,
            $_results, //result of query
            $_count = 0; //count of results

    private function __construct() {
        try { //try to connect to the database
            $dbHost = env("DB_HOST", "127.0.0.1");
            $dbName = env("DB_DATABASE", "e3mly");
            $dbUsername = env("DB_USERNAME", "root");
            $dbPassword = env("DB_PASSWORD", "");
            $this->_pdo = new PDO('mysql:host=' . $dbHost . ';dbname='. $dbName, $dbUsername, $dbPassword); 
        } catch(PDOException $ex) {
            die($ex->getMessage());
        }
    }

    private static function getInstance() { // to connect once to the database
        if(!isset(self::$_instance)) {
            slef::$_instance = new CustomDB();
        }
        return self::$_instance;
    }
    //execute regular queries and can bind ? with values
    public function query($sql, $paramters = array()) {
        $this->_error = false;
        if($this->_query->$this->$_pdo->prepare($sql)) {
            if(count($params)) { //to concatenate parameters before excute query
                $counter = 1;
                foreach($paramters as $parameter) {
                    $this->_query->bindValue($counter, $parameter); // assign parameter to the counter number ? mark
                    $counter++;
                }
            }
            if($this->_query->execute()) { //excute query
                $this->$_results = $this->_query->fetchAll(PDO::FETCH_OBJ); //return rows as objects
                $this->$_count = $this->_query->rowCount(); //count the number of rows
            } else {
                $this->$_error = true;
            }
        }
        return $this; // to chain it as query_name->error()
    }

    // getters
    public function error() { //return true if there is an error in the query
        return $this->$_error;
    }
    public function results() { 
        return $this->$_results;
    }
    public function count() {
        return $this->$_count;
    }  
    public function insert($table, $cols) {
        if(count($cols)) {
            $keys = array_kets($cols);
            $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES (" . implode(', ', $cols) . ")";
            if(!$this->query($sql)->error()) {
                return true;
            }
        }
        return false;
    }

This is my Service Provider DBServiceProvider:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class DBServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        require_once app_path('Helpers/DB/CustomDB.php');
    }
}

Then I added in providers and aliases (app/http/config/app.php):

Added Provider:

App\Providers\DBServiceProvider::class,

Added aliase:

'C_DB' => App\Facades\CustomDB::class,

Then I wrote my controller to test it:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Post; //for using model functions
use Carbon\Carbon;

use C_DB;

class PostsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth'); //redirect to login page if not logged in 
    }

    public function index()
    {
        $posts = Post::orderBy('created_at', 'desc')->paginate(5); //TODO
        return view('posts.index')->with('posts', $posts);
    }
    public function create()
    {
        return view('posts.create');
    }

    public function store(Request $request)
    {
        //validation
        $this->Validate($request, [
            'title' => 'required',
            'body' => 'required',
            'min_cost' => 'required',
            'max_cost' => 'required',
            'period' => 'required',
            'category' => 'required',
            'description_file' => 'nullable|max:1999',
        ]);
        //Handle File Upload
        if($request->hasFile('description_file'))
        {
            $file = $request->file('description_file');
            //get file name with ext
            $fileNameWithExt = $file->getClientOriginalName();
            //get just filename
            $fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
            //get just ext
            $extension = $file->guessClientExtension();
            if($extension == 'pdf')
            {
                $fileNameToStore = $fileName.'_'.time().'.'.$extension;
                //upload file
                $path = $file->storeAs('public/ProjectDescriptions', $fileNameToStore);
            }
            else
            {
                $fileNameToStore = 'nofile.pdf';
            }
        }
        else
        {
            $fileNameToStore = 'nofile.pdf';
        }
        $title = $request->input('title');
        $body = $request->input('body');
        $min_cost = (int)$request->input('min_cost');
        $max_cost = (int)$request->input('max_cost');
        $period = (int)$request->input('period');
        $user_id = Auth::id();
        $category = htmlspecialchars($request->input('category'),ENT_NOQUOTES, 'UTF-8'); 
        $created_at = Carbon::now()->toDateTimeString();
        $check = C_DB::getInstance()->insert("users", array(
            'title' => $title,
            'body' => $body,
            'min_cost' => $min_cost,
            'max_cost' => $max_cost,
            'description_file' => $fileNameToStore,
            'period' => $period,
            'user_id' => $user_id,
            'category' => $category,
            'created_at' => $created_at
        ));
        if($check) {
            return redirect('/posts')->with('success', 'Post Created');
        } else {
            return redirect('/posts')->with('failed', 'Post Faild');
        }
    }
}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2P3rC4P
via IFTTT

Aucun commentaire:

Enregistrer un commentaire