Что Вы назвали бы этим классом CRUD?

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

Он запускается планировщиком задач каждые 10 минут, сначала проверяет, есть ли подключение к Интернету, и, если да, проверяет, изменился ли мой публичный IP-адрес, и только в этом случае обновляет DNS cloudflare через их API.

Я анонимизировал свои личные идентификаторы и URL-адрес API, очевидно, вам нужно их изменить.

@echo off
cls
setlocal EnableExtensions EnableDelayedExpansion
set logFile=.\UpdatePublicIP.log
call :log "--- SCRIPT STARTED ---"
goto TestInternet

:log
echo [!date! !time!] %~1
echo [!date! !time!] %~1 >>%logFile%
exit /b 0

:TestInternet
REM First test for internet connectivity.
call :log "Detecting internet."
PING -n 1 8.8.8.8|find "Reply from " >NUL
IF NOT ERRORLEVEL 1 goto :CheckPublicIP
IF     ERRORLEVEL 1 goto :NoInternet

:NoInternet
call :log "No internet, nothing to do."
goto End

:CheckPublicIP
call :log "Detecting public IP."
for /f %%A in (
  'powershell -command "(Invoke-Webrequest "http://api.ipify.org").content"'
) do (
      set TempPublicIP=%%A
     )
call :log "Current Public IP: %TempPublicIP%"
if not "%TempPublicIP%"=="%PublicIP%" (
    call :log "Saved IP [%PublicIP%] different to current [%TempPublicIP%] IP, updating saved PublicIP."
    REM Note: setx saves env var but only available in future cmd windows, not current one.
    setx PublicIP %TempPublicIP% >nul
    goto UpdateDNS
    ) else (
            call :log "Current IP = saved IP, nothing to do."
           )
goto End

:UpdateDNS
call :log "Updating CloudFlare DNS record to [%TempPublicIP%]."
curl -X PUT "https://api.cloudflare.com/client/v4/zones/12345abcde12345abcde12345abcde12/dns_records/1234567890qwertyuiop0987654321ab" -H "X-Auth-Email: yourusername@hotmail.com" -H "X-Auth-Key:a123b4567c8defghijklmnopqrstuvwxyz123" -H "Content-Type: application/json" --data "{\"type\":\"A\",\"name\":\"yourdomainname.net\",\"content\":\"%TempPublicIP%\"}"|findstr.exe modified_on >nul
REM Can't use "success":true due to the quote. Assuming the string "modified_on" occurs on success only.
IF NOT ERRORLEVEL 1 goto :CloudFlareSuccess
IF     ERRORLEVEL 1 goto :CloudFlareError
goto End

:CloudFlareSuccess
call :log "CloudFlare DNS update succeeded.
goto End

:CloudFlareError
call :log "CloudFlare DNS update failed.
goto End

:End
call :log "--- SCRIPT FINISHED ---"
8
задан T.E.D. 8 May 2009 в 18:39
поделиться

10 ответов

Naming is difficult if is not respected SRP :) But members naming is often misused.

In your case I'll do something like this:

  • the responsibility of implementation is to cover specified contract of persistence
  • "who" is under fire

Thinks without voice - persistence is done for user and a relevant name can be IUserRepository - methods are not more than for CRUD - because of the fact that the IUserRepository is for user, is not necessary to have UserSave, UserUpdate because it brakes the generic usage manner

The Magic Is Here ... just do this:

public interface IRepository<TYPE, KEY>{
  IList<TYPE> GetAll(KEY key);
  TYPE GetById(KEY key);
  void Save(TYPE obj);
  void Update(TYPE obj);
  void Delete(Key key);
}

Is it difficult ? What to do with a custom one?

public interface IUserRepository : IRepository<User, int>
{
   IList<User> GetAllMyFavorites(ICriteria crit);
   IList<Events> GetHistoryByUser(User user);   
}

In the code using an IoC container you can do easily

public UserController {
  private _userRepository = null;
  private _eventsRepository = null;

  public UserController(IUserRepository userRepository, 
  IRepository<Events,int> eventsRepository) 
  // if you are doing here just CRUD use the generic signature
  {
    _userRepository = userRepository;
    _eventsRepository = eventsRepository;
  }

  public MarkItAsGoldPartener(int userId){
     var user = userRepository.GetById(userId);
     user.PartnerType = PartnerTypes.Gold;
     userRepository.Save(user); // the user in member name is useless
     eventsRepository.Save(new Event(){Message = "The user" + UserId + "is golden" });
  }
} 

good luck :)

7
ответ дан 5 December 2019 в 06:39
поделиться

IUserRepository - как в шаблоне Repository .

3
ответ дан 5 December 2019 в 06:39
поделиться

Я поддерживаю призыв ChrisW просто называть его «Пользователь».

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

5
ответ дан 5 December 2019 в 06:39
поделиться

Я предпочитаю IUserStorage или IUserStore

2
ответ дан 5 December 2019 в 06:39
поделиться

IUserRepository или IUserServices.

2
ответ дан 5 December 2019 в 06:39
поделиться

Почему не только IUserCRUD? CRUD не имеет 10 значений.

1
ответ дан 5 December 2019 в 06:39
поделиться

Тот факт, что у вас возникли проблемы с присвоением имени, должен быть огромным сигналом того, что это неправильно.

Здесь применяется принцип единой ответственности (и принцип разделения интерфейса). Разбейте его на различные операции, которые вам нужны.

public interface IUserList
{
    IList<User> FetchUsers();
}

public interface IUser
{
   User FetchUser(int userId);
}

public interface IUserStore
{
    bool SaveUser(User user);
    bool DeleteUser(int userId);
}

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

2
ответ дан 5 December 2019 в 06:39
поделиться

Как насчет того, чтобы назвать его «Пользователи» (или «Авторизованные пользователи», или «Коллекции пользователей»)?

1
ответ дан 5 December 2019 в 06:39
поделиться

It could become a generic interface.

ICrud<T> { }

Or inspired by IUserStore.

IStore<T> { }
2
ответ дан 5 December 2019 в 06:39
поделиться

I'd go with UserActions. This describes the set of functionality you want to do; it avoids the trap of calling it a collection (since it doesn't actually collect anything, simply retrieves a collection).

But I'd also rethink having this class in this form in the first place. It looks like what you're trying to put in place is a persistence manager; are there any other types of objects that you're going to want to persist in this manner? Can you extract any common functionality that can then be derived to a base class? Perhaps a "PersistenceManager" class or somesuch? Then, if it's absolutely necessary (and I'm not certain it would be), you could derive a "UserPersistenceManager" that would operate on User objects alone. (I believe it might not be necessary because you may be able to perform everything you need just from the PersistenceManager; only your specific implementation can tell you that, though.)

0
ответ дан 5 December 2019 в 06:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: