Creating yii2 dynamic pages with url: www.example.com/pageName - php

In my system, users need to have their profile pages. It is requested from me that these pages will be displayed in url like this:
www.example.com/John-Doe
www.example.com/Mary-Smith
How to achieve these URLs in yii2 ? These John-Doe and Mary-Smith can be user usernames or profile names. For example I have field in user table called "name" and it will hold names "John Doe", "Mary Smith". Pay attention that I need SEO friendly URLs with "-" instead of blank spaces.
URLs like this:
www.example.com/profile/view?id=1
are not an option.

www.example.com/John-Doe
www.example.com/Mary-Smith
I think there is no normal way to use these urls because at first controller (in your case it's ProfileController) needs to be determined. From these urls it's impossible to do.
Second problem with the urls you provided - uniqueness is not guaranteed. What if another user with name John Doe will sign up on site?
Look for example at your profile link at Stack Overflow:
http://stackoverflow.com/users/4395794/black-room-boy
It's not http://stackoverflow.com/black-room-boy and not even http://stackoverflow.com/users/black-room-boy.
Combining id and name is more widespread and robust approach. Also they can be combined with dash like this: http://stackoverflow.com/users/4395794-black-room-boy
Yii 2 has built-in behavior for this, it's called SluggableBehavior.
Attach it to your model:
use yii\behaviors\SluggableBehavior;
public function behaviors()
{
return [
[
'class' => SluggableBehavior::className(),
'attribute' => 'name',
// In case of attribute that contains slug has different name
// 'slugAttribute' => 'alias',
],
];
}
For your specific url format you can also specify $value:
'value' => function ($event) {
return str_replace(' ', '-', $this->name);
}
This is just an example of generating custom slug. Correct it according to your name attribute features and validation / filtering before save.
Another way of achieving unique url is setting $ensureUnique property to true.
So in case of John-Doe existense John-Doe-1 slug will be generated and so on.
Note that you can also specify your own unique generator by setting $uniqueSlugGenerator callable.
Personally I don't like this approach.
If you choose the option similar to what Stack Overflow uses, then add this to your url rules:
'profile/<id:\d+>/<slug:[-a-zA-Z]+>' => 'profile/view',
In ProfileController:
public function actionView($id, $slug)
{
$model = $this->findModel($id, $slug);
...
}
protected function findModel($id, $slug)
{
if (($model = User::findOne(['id' => $id, 'name' => $slug]) !== null) {
return $model;
} else {
throw new NotFoundHttpException('User was not found.');
}
}
But actually id is enough to find user. Stack Overflow does redirect if you access with correct id but different slug. The redirects occurs when you are completely skipping the name too.
For example http://stackoverflow.com/users/4395794/black-room-bo redirects to original page http://stackoverflow.com/users/4395794/black-room-boy to avoid content duplicates that are undesirable for SEO.
If you want use this as well, modify findModel() method like so:
protected function findModel($id)
{
if (($model = User::findOne($id) !== null) {
return $model;
} else {
throw new NotFoundHttpException('User was not found.');
}
}
And actionView() like so:
public function actionView($id, $slug = null)
{
$model = $this->findModel($id);
if ($slug != $model->slug) {
return $this->redirect(['profile/view', ['id' => $id, 'slug' => $model->slug]]);
}
}

Related

CodeIgniter 4 - Validation Custom Rule Function Quandry

In my CI4 learning, I have started by trying to simulate user sign in functionality. I have a Controller, two Views (not shown here, but really simply pages- one a pretty much just single form, and the other one a “blank” success HTML page), a set of custom rules in the Validation.php file, and a CustomRule.php file with the first of the methods that will implement all my custom rules (which, ultimately, I’d like to have all set in the Validation.php file). For lack of a better idea, I’ve stuck the CustomRules.php file in the app\Config\ folder.
Here is my problem:
For the life of me, I can’t figure out how to get the Validation service to pass additional parameters (from the form) to my custom rules function called ‘user_validated’. The CI4 documentation describes what the custom function needs to cater for when accepting additional parameters, but not how to trigger the Validation service to pass these additional parameters to one’s custom function… so although ‘user_validated’ is called, only ‘user_email_offered’ is ever passed as in as a string- nothing else goes in, from what I can tell. How do I get around this?
I have tried inserting < $validation->setRuleGroup('user_signin'); > before the call to validate, but found that I could move the setting of the rule group into the call to validate, using: $validationResult = $this->validate('user_signin'), which seemed to do the same, and which doesn't seem to work without the rule-group as a parameter (?). This still doesn't seem to be what triggers the additional data to be passed to the custom rule's method.
Extracts from my hack are appended below.
I’d be very grateful one of you knowledgeable folk could please point me in the right direction.
In app\Controllers\SignupTest.php:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class SignupTest extends BaseController
{
public function index() { // redirection from the default to signup(), signin(), ...
return $this->signup();
}
public function signup() {
helper(['form']);
$validation = \Config\Services::validation();
if ($this->request->getPost()) { // still TBD: any different to using $this->request->getGetPost() ?
$validationResult = $this->validate('user_signin'); // set the rules to use: 'user_signin', 'user_signup'
if (!$validationResult) {
$validationErrors = $validation->getErrors();
return view('SignupTestView', $validationErrors); // redisplay simple html form view with list of validation errors
} else {
return view('SignupTestViewSuccess'); // display view to show success
}
} else {
return view('SignupTestView'); // initial display, in the event of there being no POST data
}
}
}
In \app\Config\CustomRules.php:
<?php
namespace Config;
use App\Models\UserModel;
//--------------------------------------------------------------------
// Custom Rule Functions
//--------------------------------------------------------------------
class CustomRules
{
public function user_validated(string $str, string $fields = NULL, array $data = NULL, string &$error = NULL) : bool{
$user_email_offered = $str;
$user_password_offered = ''; // to be extracted using $fields = explode(',', $fields), but $fields is never provided in the call to this user_validated method
if (($user_email_offered !== NULL) && ($user_password_offered !== NULL)) {
$usermodel = new UserModel(); // intended to create a UserEntity to permit connectivity to the database
$user_found = $usermodel->find($user_email_offered); // we're going to assume that user_email is unique (which is a rule configured in the database table)
if ($user_found === NULL) { // check if user exists before doing the more involved checks in the else-if section below, which may throw exceptions if there's nothing to compare (?)
...
}
}
In \app\Config\Validation.php:
?php
namespace Config;
class Validation
{
//--------------------------------------------------------------------
// Setup
//--------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* #var array
*/
public $ruleSets = [
\CodeIgniter\Validation\Rules::class,
\CodeIgniter\Validation\FormatRules::class,
\CodeIgniter\Validation\FileRules::class,
\CodeIgniter\Validation\CreditCardRules::class,
\Config\CustomRules::class,
];
/**
* Specifies the views that are used to display the
* errors.
*
* #var array
*/
public $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
//--------------------------------------------------------------------
// Custom Rules
//--------------------------------------------------------------------
/* configurable limits for validation rules array below*/
const user_email_min_lenth = 9;
const user_email_max_lenth = 50;
const user_password_min_lenth = 6;
const user_password_max_lenth = 25;
public $user_signin = [
'user_email' => [
'label' => 'e-mail address',
'rules' => 'trim|required|valid_email|user_validated', // user_validated is custom rule, that will have a custom error message
'errors' => [
'required' => 'You must provide an {field}',
'valid_email' => 'Please enter a valid {field}',
]
],
'user_password' => [
'label' => 'password',
'rules' => 'trim|required',
'errors' => [
'required' => 'Enter a {field} to sign in',
'user_password_check' => 'No such user/{field} combination found',
]
Calling custom rule with parameters should be exactly the same as calling CI4's regular rules. Let's get for example "required_without". You use it like in this example:
$validation->setRule('username', 'Username', 'required_without[id,email]');
And the function is declared as so:
public function required_without($str = null, string $fields, array $data): bool
{
$fields = explode(',', $fields);
//...
}
where $str - this is your main field, $fields - string, packing a comma-separated array.
As for Grouping rules, you do not need to group rules to be able to use custom rules with parameters.
If you have only 2 fields to test against you can go a bit cheaper, which will not be perfect but still works:
Function:
public function myrule(string $mainfield, string $fieldtotestwith): bool
{
//doing stuff
}
Validating rule:
$validation->setRule('somemainfield', 'Something', 'myrule[somesecondfield]');

How to avoid duplication in Laravel validation rules

For validating form validation rules I currently stored them in User Model and use it in Register Controller, User controller in admin panel, User Controller in APIs and some other places, but currently it's very hard to maintain because each controller needs a slightly different set of rules and when I change the rules in User Model other controllers will not work anymore. So how to avoid duplication in rules and still keep the code maintainable?
Approach I often use is to write a HasRules trait for my models, it looks something like this:
trait HasRules
{
public static function getValidationRules(): array
{
if (! property_exists(static::class, 'rules')) {
return [];
}
if (func_num_args() === 0) {
return static::$rules;
}
if (func_num_args() === 1 && is_string(func_get_arg(0))) {
return array_get(static::$rules, func_get_arg(0), []);
}
$attributes = func_num_args() === 1 && is_array(func_get_arg(0))
? func_get_arg(0)
: func_get_args();
return array_only(static::$rules, $attributes);
}
}
Looks messy, but what it does is allows you to retrieve your rules (from a static field if such exists) in a variety of ways. So in your model you can:
class User extends Model
{
use HasRules;
public static $rules = [
'name' => ['required'],
'age' => ['min:16']
];
...
}
Then in your validation (for example, in your FormRequest's rules() method or in your controllers when preparing rules array) you can call this getValidationRules() in variety of ways:
$allRules = User::getValidationRules(); // if called with no parameters all rules will be returned.
$onlySomeRules = [
'controller_specific_field' => ['required'],
'name' => User::getValidationRules('name'); // if called with one string parameter only rules for that attribute will be returned.
];
$multipleSomeRules = User::getValidationRules('name', 'age'); // will return array of rules for specified attributes.
// You can also call it with array as first parameter:
$multipleSomeRules2 = User::getValidationRules(['name', 'age']);
Don't be afraid to write some code for generating your custom controller specific rules. Use array_merge and other helpers, implement your own (for example, a helper that adds 'required' value to array if it's not there or removes it etc). I strongly encourage you to use FormRequest classes to encapsulate that logic though.
You can try using laravel's validation laravel documentation
it is really easy to use and maintain just follow these steps:
run artisan command: php artisan make:request StoreYourModelName
which will create a file in App/Http/Requests
in the authorize function set it to:
public function authorize()
{
return true;
}
then write your validation logic in the rules function:
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
Custom error messages add this below your rules function:
public function messages()
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
Lastly to use this in your controller just add it as a parameter in your function.
public function create(Request $request, StoreYourModelName $storeYourModelName)
{
//
}
and that's all you need to do this will validate on form submission if validation passes it will go to your controller, keep in mind your validation logic does not have to be like mine thought i would show you one way that it can be done..

Filtering data in laravel and handling the views

I have a tv show netflix-esque project I'm building where I have a Shows page which I want to filter on format. Each show contains episodes which can have a tv, dvd and bd format.
Currently I'm filtering using separate routes and controllers which extend the base ShowsController.
Route::get('shows/view/{type}', ['as' => 'shows.viewtype', 'uses' => 'ShowsController#viewType',]);
Route::get('shows/bluray',['as' => 'shows.bluray','uses' => 'ShowsBlurayController#index']);
Route::get('shows/dvd',['as' => 'shows.dvd','uses' => 'ShowsDVDController#index']);
Route::get('shows/tv',['as' => 'shows.tv','uses' => 'ShowsTVController#index']);
Example of one of the format controllers
class ShowsBlurayController extends ShowsController
{
public function index()
{
// Set user state for browsing bluray
Session::push('user.showtype', 'bluray');
$shows = $this->show->getBlurayPaginated(16);
return $this->getIndexView(compact('shows'));
}
}
I use the getIndexView() method (in the ShowsController) to determine one of 2 available views: poster and list.
public function getIndexView($shows)
{
$viewType = get_session_or_cookie('show_viewtype', 'list');
if ($viewType == 'posters') {
return View::make('shows.index', $shows)
->nest('showsView', 'shows.partials.posters', $shows);
} else {
return View::make('shows.index', $shows)
->nest('showsView', 'shows.partials.list', $shows);
}
}
The shows are filtered based on the episodes:
public function getBlurayPaginated($perPage)
{
return $this->getByFormat('BD')->with('tagged')->paginate($perPage);
}
private function getByFormat($format)
{
return $this->show->whereHas('episodes', function ($q) use ($format) {
$q->whereHas('format', function ($q) use ($format) {
$q->where('format', '=', $format);
});
});
}
The problem is that I want to do this in a clean way. When a user selects a format, that filter will be applied. Currently all of this is kind of scattered across controllers and doesn't quite make sense.
I also thought of doing something like this in the routes.php:
Route::get('shows/format/{format}',['as' => 'shows.format','uses' => 'ShowsController#index']);
And then handle the filtering in the index, but that also seems a weird place to do that.
This approach does work, but I don't want to screw myself later on with it. I'm planning a simple search which should take the filter into account.
In other words, how can I organize the code in such a way that getting data from the database will take the filter into account which has been set? (Session states maybe?)
Route::get('shows/format/{format}',[
'as' => 'shows.format',
'uses' => 'ShowsController#index'
]);
I think you're on the right track here. I would go so far as to produce a factory and inject it into the controller. The purpose of this factory is to construct a formatter that will supply your view with the correct data:
// ShowController
public function __construct(ShowFormatFactory $factory, ShowRepository $shows)
{
$this->factory = $factory;
// NB: using a repository here just for illustrative purposes.
$this->shows = $shows;
}
public function index($format = null)
{
$formatter = $this->factory->make($format);
return View::make('shows.index', [
'formatter' => $formatter,
'shows' => $this->shows->all(),
]);
}
// ShowFormatFactory
class ShowFormatFactory
{
public function make($format)
{
switch($format) {
case 'blueray':
return new BluerayFormat(); break;
case 'dvd': /* Fallthrough for default option */
default:
return new BluerayFormat(); break;
}
}
}
// ShowFormatInterface
interface ShowFormatInterface
{
public function format(Show $show);
}
// BluerayFormat
class BluerayFormat implements ShowFormatInterface
{
public function format(Show $show)
{
return $show->blueray_format;
}
}
Then in your view, since you are guaranteed to have an object that will provide you the format requested for a given show, just call it:
#foreach($shows as $show)
<div class="show">
Chosen Format: {{ $formatter->format($show) }}
</div>
#endforeach
This solution is testable and extensible will allow you to add other formats later on. If you do, you would need to add a discrete case statement in the factory for each different format, as well as write a rather slim ~5-7 line class to support the new format.

How to use beforeAction in Yii or slug troubles

Yii-jedis!
I'm working on some old Yii-project and must to add to them some features. Yii is quite logical framework but it has some things I couldn't understand. Perhaps I haven't understand Yii-way yet. So I'll describe my problem step-by-step. For impatients - briefly question at the end.
Intro: I want to add human-readable URLs to my project.
Now URLs looks like: www.site.com/article/359
And I want them to look like this: www.site.com/article/how-to-make-pretty-urls
Very important: old articles must be available on old format URLs, and new - on new URLs.
Step 1: First, I've updated rewrite rules in config/main.php:
'<controller:\w+>/<id:\S+>' => '<controller>/view',
And I've added new texturl column to article table. So we will store here human-readable-part-of-url for new articles. Then I've updated one article with texturl for tests.
Step 2: Application show articles in actionView of ArticleController so I've added there this code for preproccessing ID parameter:
if (is_numeric($id)) {
// User try to get /article/359
$model = $this->loadModel($id); // Article::model()->findByPk($id);
if ($model->text_url !== null) {
// If article with ID=359 have text url -> redirect to /article/text-url
$this->redirect(array('view', 'id' => $model->text_url), true, 301);
}
} else {
// User try to get /article/text-url
$model = Article::model()->findByAttributes(array('text_url' => $id));
$id = ($model !== null) ? $model->id : null ;
}
And then begin legacy code:
$model = $this->loadModel($id); // Load article by numeric ID
// etc
It works perfectly! But...
Step 3: But we have many actions with ID parameter! What we have to do? Update all actions with that code? I think it's ugly. I've found CController::beforeAction method. Looks good! So I declare beforeAction and place ID preproccessing there:
protected function beforeAction($action) {
$actionToRun = $action->getId();
$id = Yii::app()->getRequest()->getQuery('id');
if (is_numeric($id)) {
$model = $this->loadModel($id);
if ($model->text_url !== null) {
$this->redirect(array('view', 'id' => $model->text_url), true, 301);
}
} else {
$model = Article::model()->findByAttributes(array('text_url' => $id));
$id = ($model !== null) ? $model->id : null ;
}
return parent::beforeAction($action->runWithParams(array('id' => $id)));
}
Yes, it works with both URL-formats, but it executes actionView TWICE and shows page two times! What can I do with this? I've totally confused. Have I choose a right way to solve my problem?
Briefly: Can I proceess ID (GET-parameter) before execute of any actions and then run requested action (once!) with modified only ID parameter?
Last line should be:
return parent::beforeAction($action);
Also to ask you i didnt get your step:3.
As you said you have many controller and you don't need to write code in each file, so you are using beforeAction:
But you have only text_url related to article for all controllers??
$model = Article::model()->findByAttributes(array('text_url' => $id));
===== updated answer ======
I have changed this function, check now.
If $id is not nummeric then we will find it's id using model and set $_GET['id'], so in further controller it will use that numberic id.
protected function beforeAction($action) {
$id = Yii::app()->getRequest()->getQuery('id');
if(!is_numeric($id)) // $id = how-to-make-pretty-urls
{
$model = Article::model()->findByAttributes(array('text_url' => $id));
$_GET['id'] = $model->id ;
}
return parent::beforeAction($action);
}
Sorry, I haven't read it all carefully but have you considered using this extension?

Perform validation only on create using php-activerecord

I am creating a User Model using Codeigniter and php-activerecord and the wiki says I can use 'on' => 'create' to have a validation only run when a new record is created, like this,
static $validates_presence_of = array(
array('title', 'message' => 'cannot be blank on a book!', 'on' => 'create')
);
It also states that we have access to "save", "update" and "delete"...
None of these are working for me though and I can figure out why, here is my code,
// Validations
static $validates_presence_of = array(
array('email', 'message' => 'Please enter a valid email address.'),
array('password', 'message' => 'Password must be provided.', 'on' => 'create')
);
I want to set it up like this so that when a user updates their profile, they can leave their password blank to keep their current one.
I would appreciate any help or guidance! Thanks!
The reason for this is most likely because it's not been implemented.
Relevant classes are lib/Model.php and lib/Validations.php
From a purely abstract standpoint, you would need to track the mode of operation between save and create. To do this, I created a public property (public $validation_mode) within lib/Model.php and set that property to 'create' or 'save' in private methods Model::insert() and Model::update() respectively. These values match the 'on' property you are trying to use.
Then within lib/Validations.php, I modified the following methods:
Validations::validates_presence_of()
public function validates_presence_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES['blank'], 'on' => 'save'));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$this->record->add_on_blank($options[0], $options['message'], $options);
}
}
Errors::add_on_blank()
public function add_on_blank($attribute, $msg, $options = array())
{
if (!$msg)
$msg = self::$DEFAULT_ERROR_MESSAGES['blank'];
if (($value = $this->model->$attribute) === '' || $value === null)
{
if(array_key_exists('on', $options))
{
if($options['on'] == $this->model->validation_mode)
{
$this->add($attribute, $msg);
}
} else {
$this->add($attribute, $msg);
}
}
}
What this does basically is passes ALL the $options specified in your model (including the 'on' property) down to the Errors::add_on_blank() method where it now has enough information to differentiate between 'on' => 'create' and the default ('on' => 'save'). Using the public $validation_mode property from the Model class ($this->model->validation_mode), we can determine what the current mode of operation is and whether or not we wish to continue adding the error message or skip it this time around.
Obviously you would want to document any changes you make and test thoroughly. According to the documentation, all validation methods supposedly support this "common option" along side allow_null, allow_blank but again, if it's not implemented, you will have to make it happen yourself by making these necessary changes.
should be call the validation method like this:
#example
$your_obj = new Instace();
if($your_obj->is_valid()) {
// if all is correct your logical code
}
else {
// your logical to show the error messages
}
//doesnt work if you write
if(!$your_obj->is_valid())
//the other way you must be use the next method
if($your_obj->is_invalid())
I'm find a answer for your question without edit library.
Add the before_validation callback and add in this callback a validation rule. It works for me.
static $before_validation_on_create = array('before_validation_on_create');
static $validates_presence_of = array(
array('login'),
);
public function before_validation_on_create() {
self::$validates_presence_of[] = array('password');
}

Categories