1. Go to this page and download the library: Download mmedia/classcontroller library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mmedia / classcontroller example snippets
use MMedia\ClassController\Http\Controllers\ClassController;
class TestClassController extends ClassController
{
protected $inheritedClass = 'MMedia\ClassController\Examples\Test';
//Done. All methods from the class Test are inherited and wrapped in Laravel validation automatically
}
// We're just using the methods in the inherited class methods directly
Route::get('/noParams', [TestClassController::class, 'noParams']); // === \Test::noParams()
Route::get('/mixedParam/{param}', [TestClassController::class, 'mixedParam']); // === \Test::mixedParam($param) + auto validation!
namespace App\Http\Controllers\Api\Test;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function noParams(Request $request)
{
$testClass = new Test();
try {
$methodResult = $testClass->noParams();
if ($request->wantsJson()) {
return response()->json($methodResult, 200);
}
return back()->with('success', $methodResult);
} catch (\Exception $e) {
return abort(400, $e->getMessage());
}
}
public function mixedParam(Request $request)
{
$validatedData = $request->validate([
'param' => ['
protected function classParameters(): iterable
{
return [$param1, $param2];
}
protected function postClassSetup(): void
{
// Your code here. You have access to $this->class().
}
public function mixedParam(Request $request)
{
// You can write your own $request->validate(), or use the one from ClassController which validates that the data passed to the original class method is correct
$validatedData = $this->getValidatedData($this->class(), 'mixedParam');
// Call the original method if you want, or override it completely
return $this->class()->mixedParam($validatedData['param']);
}
use MMedia\ClassController\ValidatesClassMethods;
class myClass
{
use ValidatesClassMethods;
/**
* Example method showing how to use the `getValidatedData` method.
*
* @param string $param1
* @param int|null $param2
* @throws ValidationException
* @return string
*/
public function test(string $param1, ?int $param2)
{
// Note: in the real world, it makes little sense to get validated data from within the same method as the method that is being called - PHP would have already thrown an error if the params were not valid types.
$validatedData = $this->getValidatedData(get_class($this), __FUNCTION__);
// Your code here. $validatedData['param1'] is a valid string and $validatedData['param2'] is a valid integer or null.
return $validatedData['param1'] . $validatedData['param2'];
}
}