اذهب إلى المحتوى
  • 0

إضافة ملف لدوال مُساعدة في Laravel

Mahmoud Alrashidi

السؤال

Recommended Posts

  • 0

يُمكنك ذلك من خلال إنشاء ملف php عادي في أي مسار تريده مثلاً في:

tests
|_ Utilities
|_|___ functions.php

و تضع الدوال التي تحتاجها فيه مثلاً:

<?php

function create($class, $attributes = []) {
    return $class::factory()->create($attributes);
}

function make($class, $attributes = []) {
    return $class::factory()->make($attributes);
}

الآن ستقوم بإضافة عملية التحميل التلقائي للملف من خلال composer و لعمل ذلك تحتاج التعديل على ملف composer.json:

إن كنت تحتاج أن تتم عملية التحميل التلقائي للملف فقط في مرحلة التطوير ستُضيف مسار الملف داخل مصفوفة files ضمن الخاصية autoload-dev:

"autoload-dev": {
  "psr-4": {
    "Tests\\": "tests/"
  },
  "files": ["tests/Utilities/functions.php"]
},

أما إن أردت أن تشمل العملية مرحلة الإنتاج فستضع مسار الملف داخل مصفوفة files في الخاصية autoload:

"autoload": {
  "psr-4": {
    "App\\": "app/",
      "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/"
  },
  "files": ["tests/Utilities/functions.php"]
},

بعد ذلك قم بتنفيذ أمر:

composer dump-autoload

ثم ستتمكن من إستخدام الدوال التي أنشأتها في أي مكان تريد، في المثال أرفقت دالتين إحداهما لإنشاء سجل جديد من نموذج معين و الثانية تُنشئ السجل و تقوم بتخزينه في قاعدة البيانات، و هاتين الدالتين تحتاج لهما كثيرا في الإختبارات: 

و هذا مثال عن إستخدامها:

<?php

/** @test */
function an_authenticated_user_may_participate_in_forum_threads()
{
  $this->signIn();

  $reply = make(Reply::class);

  $this->post($this->thread->path . "/replies", $reply->toArray());

  $this->get($this->thread->path)
    ->assertSee($reply->body);
}

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

صحيح أنه يمكنك وضع الدوال المساعدة في أي مكان تريده ولكن المتعارف عليه أن يكون بداخل مجلد App مباشرة أو في المسار App/Http أو هنالك من ينشئ مجلداً خاصة في المجلد App ويعيطه الاسم Helpers ثم بداخله يضع الملف الذي سيحتوي على الدوال المساعدة ويمكنك بهذه الحالة تنظيم الدوال المساعدة حسب كل فئة لتنظيم الكود أكثر. كذلك التسمية المعروفة لهذا الملف هي helpers ولكن بالطبع يمكنك تسميته بأي اسم تريده.

هذه بعض الأمور المتعارف عليها حيث في حال قام أي شخص آخر برؤية الكود سيعرف أن هذا هو الملف للدوال المساعدة, لكن بالطبع يمكنك التعديل عليه كما تريد في حال تم التوضيح على ان هذا الملف هو للدوال المساعدة. باقي الأمور من تعريف المشروع على ملف الدوال تم ذكره في الرد السابق.

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

يمكنك في المسار التالي 

maiproject\app

صنع مجلد جديد وليكن باسم Helpers ثم في داخل المجلد هذا نضع ملف اسمه helpers.php. ومن ثم فليكن الملف بداخله هكذا 

<?php

if (! function_exists('create_option')) {
	function create_option($table = '',$value = '',$show = '',$selected = '', $where = null) {
		if($where != null){
			$results = DB::table($table)->where($where)->orderBy('id','DESC')->get();
		}else{
			$results = DB::table($table)->orderBy('id','DESC')->get();
		}
		$option = '';
		foreach ($results as $data) {
			if($data->$value == $selected){
				$option .= '<option value="' . $data->$value . '" selected>' . (isset(unserialize($data->$show)[get_option('language')]) ? unserialize($data->$show)[get_option('language')] : '') . '</option>';
			}else{
				$option .= '<option value="' . $data->$value . '">' . (isset(unserialize($data->$show)[get_option('language')]) ? unserialize($data->$show)[get_option('language')] : '') . '</option>';
			}
		}
		echo $option;
	}
}

if ( ! function_exists('get_row')){
	function get_row($table, $where = null , $order = 'ASC') 
	{
		if($where != null){
			$row = DB::table($table)->where($where)->orderBy('id', $order)->first();
		}else{
			$row = DB::table($table)->orderBy('id', $order)->first();
		}
		return $row;
	}
}

if ( ! function_exists('get_table')){
	function get_table($table, $where = null , $order = 'DESC') 
	{
		if($where != null){
			$results = DB::table($table)->where($where)->orderBy('id', $order)->get();
		}else{
			$results = DB::table($table)->orderBy('id', $order)->get();
		}
		return $results;
	}
}

if ( ! function_exists('get_logo')){
	function get_logo() 
	{
		$logo = get_option("logo");
		if($logo == ''){
			return asset("public/uploads/images/default-logo.png");
		}
		return asset("public/uploads/images/$logo"); 
	}
}

if ( ! function_exists('get_icon')){
	function get_icon($name) 
	{
		return asset("public/images/icons/".$name); 
	}
}

if ( ! function_exists('month_number_to_name')){
	function month_number_to_name($month_number) 
	{
		$month_name = date("F", mktime(0, 0, 0, $month_number, 10));
		return $month_name; 
	}
}

if ( ! function_exists('sql_escape')){
	function sql_escape($unsafe_str) 
	{
		if (get_magic_quotes_gpc())
		{
			$unsafe_str = stripslashes($unsafe_str);
		}
		return $escaped_str = str_replace("'", "", $unsafe_str);
	}
}

if ( ! function_exists('get_option')){
	function get_option($name, $optional = '') 
	{
		$setting = DB::table('settings')->where('meta_key', $name)->get();
		if ( ! $setting->isEmpty() ) {
			return $setting[0]->meta_value;
		}
		return $optional;

	}
}

if ( ! function_exists('timezone_list'))
{
	function timezone_list() {
		$zones_array = array();
		$timestamp = time();
		foreach(timezone_identifiers_list() as $key => $zone) {
			date_default_timezone_set($zone);
			$zones_array[$key]['ZONE'] = $zone;
			$zones_array[$key]['GMT'] = 'UTC/GMT ' . date('P', $timestamp);
		}
		return $zones_array;
	}

}

if ( ! function_exists('create_timezone_option'))
{

	function create_timezone_option($old="") {
		$option = "";
		$timestamp = time();
		foreach(timezone_identifiers_list() as $key => $zone) {
			date_default_timezone_set($zone);
			$selected = $old == $zone ? "selected" : "";
			$option .= '<option value="'. $zone .'"'.$selected.'>'. 'GMT ' . date('P', $timestamp) .' '.$zone.'</option>';
		}
		echo $option;
	}

}


if ( ! function_exists( 'get_country_list' ))
{
	function get_country_list($selected = '') {	
		if( $selected == "" ){
			echo file_get_contents( app_path().'/Helpers/country.txt' );
		}else{
			$pattern = '<option value="'.$selected.'">';
			$replace = '<option value="'.$selected.'" selected="selected">';
			$country_list = file_get_contents( app_path().'/Helpers/country.txt' );
			$country_list = str_replace($pattern, $replace, $country_list);
			echo $country_list;
		}
	}	
}

if( !function_exists('load_language') ){
	function load_language($active=''){
		$path = resource_path() . "/_lang";
		$files = scandir($path);
		$options = "";
		
		foreach($files as $file){
			$name = pathinfo($file, PATHINFO_FILENAME);
			if($name == "." || $name == "" || $name == "language"){
				continue;
			}
			
			$selected = "";
			if($active == $name){
				$selected = "selected";
			}else{
				$selected = "";
			}
			
			$options .= "<option value='$name' $selected>".ucwords($name)."</option>";

		}
		echo $options;
	}
}

if( !function_exists('get_language_list') ){
	function get_language_list(){
		$path = resource_path() . "/_lang";
		$files = scandir($path);
		$array = array();

		$default = get_option('language');
		$array[] = $default;
		
		foreach($files as $file){
			$name = pathinfo($file, PATHINFO_FILENAME);
			if($name == "." || $name == "" || $name == "language" || $name == $default){
				continue;
			}

			$array[] = $name;

		}
		return $array;
	}
}

if ( ! function_exists('counter')){
	function counter($table, $where = null) 
	{
		if($where != null){
			$results = DB::table($table)->where($where)->count();
		}else{
			$results = DB::table($table)->count();
		}
		return $results;
	}
}

if ( ! function_exists('count_inbox')){
	function count_inbox() 
	{
		$inbox = App\ContactMessage::where('status', 0)->count();
		return $inbox;
	}
}

if (! function_exists('is_site_installed')) {
    function is_site_installed()
    {
        return is_file(public_path('install.txt'));
    }
}

ملاحظة هذا الكود مجرد مثال. 

ثم في ملف composer.json نضع بداخل السطر التالي 

"autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },

فيكون 

"autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "app/Helpers/helpers.php"
        ],
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },

ثم نقوم بتنفيذ هذا الامر داخل terminal 

composer dump-autoload

وهكذا نكون قد أضفنا هذا الملف للمشروع بكل سهولة.

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...